#列表快速生成
a = [x**3+100 for x in range(1,11)]
print(a)
b =[[0]*8]*10
print(b)
c = [[l*r for r in range(1,9)]for l in range(1,10)]#行号乘列号
print(c)
d = [x*x for x in range(90,100)if x % 3 == 0]
print(d)
e1 = [x+y for x in '我爱你' for y in '1314']
print(e1)
e2 = [[x+y for x in '我爱你']for y in '1314']
print(e2)
e3 = ['我爱你'[x]+'1314'[x] for x in range(3)]
print(e3)
OUTPUT
[101, 108, 127, 164, 225, 316, 443, 612, 829, 1100]
[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0,
0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
[[1, 2, 3, 4, 5, 6, 7, 8], [2, 4, 6, 8, 10, 12, 14, 16], [3, 6, 9, 12, 15, 18, 21, 24], [4, 8, 12, 16, 20, 24, 28, 32], [5, 10, 15, 20, 25, 30, 35, 40], [6, 12, 18, 24, 30,
36, 42, 48], [7, 14, 21, 28, 35, 42, 49, 56], [8, 16, 24, 32, 40, 48, 56, 64], [9, 18, 27, 36, 45, 54, 63, 72]]
[8100, 8649, 9216, 9801]
['我1', '我3', '我1', '我4', '爱1', '爱3', '爱1', '爱4', '你1', '你3', '你1', '你4']
[['我1', '爱1', '你1'], ['我3', '爱3', '你3'], ['我1', '爱1', '你1'], ['我4', '爱4', '你4']]
['我1', '爱3', '你1']
比特(bit)
比特,计算机专业术语,是信息量单位,由英文BIT音译而来。BIT为Binary digit(二进制数)位的缩写。二进制数的一位所包含的信息就是一比特,如二进制数0100就是4比特。16比特所能表达的最大数字:2**(16-1)
字节(byte)
在二进制数系统中,每个0或1就是一个位(bit),位是数据存储的最小单位。其中8bit就称为一个字节(Byte)。计算机中的CPU位数指的是CPU一次能处理的最大位数。例如32位计算机的CPU一次最多能处理32位数据。
K
计算机中,K表示2的十次方即1024。
5.2.2
my_set = {
x for x in 'abcdefg'}
my_set.add('h')#集合中添加一个元素
#append用于列表,因为append意思为在文章后面增补
print(my_set)
5.2.3集合运算
#集合运算
#子集,超集
s1 = {
x for x in range(512)}
s2 = {
y for y in range(928)}
print(s1.issubset(s2),s2.issuperset(s1))
#交(&)并(|)差(-)补(^)
#补集是指a|b - a&b
s3 = {
1,2,3,4}
s4 = {
3,4,5,6}
print(s3 & s4)
print(s3 | s4)
print(s3 - s4)
print(s3 ^ s4)
True True
{
3, 4}
{
1, 2, 3, 4, 5, 6}
{
1, 2}
{
1, 2, 5, 6}
#序列解包,*
s = '超 脑 说 要 有 光'.split( )
*x,y = s
print(x,y)
*x,y,z = s
print(x,y,z)
x,*y,z = s
print(x,y,z)
first,second,*rest = s
print(first,second,rest)
输出
['超', '脑', '说', '要', '有'] 光
['超', '脑', '说', '要'] 有 光
超 ['脑', '说', '要', '有'] 光
超 脑 ['说', '要', '有', '光']
#exec() 与 eval()
#exec(字符串,名字空间(字典))
exec("print(\"浮舟沧海,立马昆仑\")")
namespace = {
}
namespace['x'] = 1
namespace['y'] = 2
exec('sum = x + y',namespace)
print('{}'.format(namespace['sum']))#注意sum在全局名字空间不存在,而是存在于后面的namespace里
#eval(字符串,名字空间(字典))
eval("print(\"浮舟沧海,立马昆仑\")")
outcome = eval("3+1-2")#eval()可以将字符串当作表达式,并返回其值,exec()没有返回值
print(outcome)
namespace1 = {
}
namespace1['x'] = 1
namespace1['y'] = 2
exec('sum = x + y',namespace1)
print('{}'.format(namespace1['sum']))
输出
浮舟沧海,立马昆仑
3
浮舟沧海,立马昆仑
2
3
#字典基本操作
#字典生成
dict1 = {
'name':'WJY','feature':'Loving WJ','hobby':'Reading, drawing'}
dict1['looks'] = 'Black curly hair'
print(dict1)
list1 = ['大海','宇宙','星云','人世间','爱情','浩瀚','光风霁月']
dict2 = {
}
for idx,thing in enumerate(list1):
dict2[idx+1] = thing
print(dict2)
list2 = list(enumerate(list1))
print(dict(list2))
dict3 = dict(CantLiveWithout = 'love')#CantLiveWithout不加引号,是因为这是dict()函数的参数
print(dict3)
#基本操作
del dict1['feature']
print(dict1)
print('feature' in dict1)
print('WJY' in dict1.values())# print('WJY' in dict1)是无法识别值是否在字典里的
#get()函数
print(dict1.get('attribute','Strength'))#有attribute则返回dict1里的对应值,无attribute则返回默认值,
#不会改变dict1,不会新增{'attribute':'Strength'}这个键值对
#get()实质:返回值
#pop():
returnStr = dict1.pop('hobby')#注意字典pop里的参数是键,返回时值
print(returnStr)
print(dict1)
#update()
dict1_new = {
'name':'WJY','feature':'Love WJ deeply ','looks':'Handsome','Hobby':'Architecture'}
dict1.update(dict1_new)
print(dict1)
#字典的遍历(键、值、键值对)
print("My little one has many aspects:")
toollist = []
for k in dict1.keys():
toollist.append(k)
print(', '.join(str(i)for i in toollist))#注意这里的表达
toollist.clear()
print("This is the answers:")
for v in dict1.values():
toollist.append(v)
print(', '.join(str(i)for i in toollist))
toollist.clear()
print("Sorry, but I want to repeat:")
for k,v in dict1.items():
toollist.append((k+': '+v))
print(', '.join(str(i)for i in toollist))
输出
{
'name': 'WJY', 'feature': 'Loving WJ', 'hobby': 'Reading, drawing', 'looks': 'Black curly hair'}
{
1: '大海', 2: '宇宙', 3: '星云', 4: '人世间', 5: '爱情', 6: '浩瀚', 7: '光风霁月'}
{
0: '大海', 1: '宇宙', 2: '星云', 3: '人世间', 4: '爱情', 5: '浩瀚', 6: '光风霁月'}
{
'CantLiveWithout': 'love'}
{
'name': 'WJY', 'hobby': 'Reading, drawing', 'looks': 'Black curly hair'}
False
True
Strength
Reading, drawing
{
'name': 'WJY', 'looks': 'Black curly hair'}
{
'name': 'WJY', 'looks': 'Handsome', 'feature': 'Love WJ deeply ', 'Hobby': 'Architecture'}
My little one has many aspects:
name, looks, feature, Hobby
This is the answers:
WJY, Handsome, Love WJ deeply , Architecture
Sorry, but I want to repeat:
name: WJY, looks: Handsome, feature: Love WJ deeply , Hobby: Architecture
#函数基础
#任意数量的参数(形参)
def myprint(title,*content):#一个*
print(title)
for x in content:
print('\t' + x)
myprint('Welcome to the hunger game:','WJ','WJY','Somebody')
def myprint2(title,**content):#两个*
print(title)
for k,v in content.items():
print('\t'+k+' aged '+str(v))
dict1 = {
'WJ':19,'WJY':20,'Somebody':37}
myprint2('Welcome to the hunger game:',WJ=19,WJY=20,Somebody=37)
#注意这里**content的表达,是关键字参数,并且只能接受关键字参数
#分配参数(实参)
def Luxuries(name,history,feature,symbol):#列表不可以
print("A luxury band:\n{
} with a history of {
},is \
wellknown with the feature of {
}. As we all know, \
{
} is its miracle of history".format(name,history,feature,symbol))
Chanel = ('Chanel','111','Camellia','Coco Chanel')
Luxuries(*Chanel)
Chaneldict = dict(name = 'Chanel',history = 111,feature = 'Camellia',symbol = 'Coco Chanel')
Luxuries(**Chaneldict)#一个*表示元组,两个**表示字典
输出
Welcome to the hunger game:
WJ
WJY
Somebody
Welcome to the hunger game:
WJ aged 19
WJY aged 20
Somebody aged 37
A luxury band:
Chanel with a history of 111,is wellknown with the feature of Camellia. As we all know, Coco Chanel is its miracle of history
A luxury band:
Chanel with a history of 111,is wellknown with the feature of Camellia. As we all know, Coco Chanel is its miracle of history
#global()
# 在函数体内用,告诉解释器如果再提到x是指全局变量中的x
def func():
global x
x = 99
y[1] = 88
print("Inside x:",x)
print("Inside y:",y)
x = 1
y = [1,2,3]
func()
print("Outside x:",x)
print("Outside y:",y)
输出
Inside x: 99
Inside y: [1, 88, 3]
Outside x: 99
Outside y: [1, 88, 3]
Inside a: 99
a after globals(): 1
{
'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002071D141820>, '__spec__': None,
'__annotations__': {
}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'd:\\PARADISE\\3.py', '__cached__': None, 'func': <function func at 0x000002071D126280>, 'x': 99, 'y': [1, 88, 3], 'func2': <function func2 at 0x000002071D381EE0>, 'a': 1}
#递归
def factorial(n):
print("{}: are you calling me?".format(n))
if n == 1:
return 1
r = n*factorial(n-1)
return r
print(factorial(7))
#二分查找法
def sortinhalf(target,range,times = 0):
range.sort()
l = len(range)
if range[l//2] == target:
return times
elif range[l//2] < target:
return sortinhalf(target,range[l//2:],times+1)#注意这里要用return 函数,
#不能return range([l//2:] 因为递归是一层一层脱开的,
#从最后一层脱开回到导数第二层,无法继续)
elif range[l//2] > target:
return sortinhalf(target,range[:l//2],times+1)
def main():
x,y = input("你想在哪个范围中查找呢?分别写下最小值,最大值:").split(',')
onerange = [i for i in range(int(x),int(y) + 1)]
target = eval(input("你想查找谁呢:"))
t = sortinhalf(target,onerange)
print('经过了{}次查找,我们找到了{}'.format(t,target))
main()
输出
7: are you calling me?
6: are you calling me?
5: are you calling me?
4: are you calling me?
3: are you calling me?
2: are you calling me?
1: are you calling me?
5040
你想在哪个范围中查找呢?分别写下最小值,最大值:1,1000
你想查找谁呢:4
经过了7次查找,我们找到了4
import TestPlace#调用同一目录下的py文件,注意没有后缀
TestPlace.main1()#不要忘记前面的内容
from Practice import Practice11_Bubblesort #调用所属目录的某个子目录
Practice11_Bubblesort.Bubblesort()
#面向对象
#创建类
from enum import Enum
class gender(Enum):
male = 0
female = 1
class Lover:
def __init__(self,sname = 'N/A',iage = 0):
self.name = sname
self.age = iage
self.height = 0
self.weight = 0
def speak(self):
print('I\'m {}……'.format(self.name))
#创建对象
wjy = Lover('WJY',20)
#children.py
from father import Lover
class Couple(Lover):
def __init__(self,iphone,sname,iage):
Lover.__init__(self,sname,iage)
self.phone = iphone
self.feature = 'cute'
def speak(self):
Lover.speak(self)
print("I still love you deeply……")
wangjunyi = Couple(13308360814,'WJY',20)
wangjunyi.speak()
print(wangjunyi.name)#注意属性名不加()
I'm WJY……
I still love you deeply……
WJY
#继承链
#chain.py
class A:
def __init__(self):
print("A")
class B(A):
def __init__(self):
print("B")
class C(B):
def __init__(self):
print("C")
class D(C):
def __init__(self):
B.__init__(self)
super(C,self).__init__()#注意这里打印的是B,因为C的父类是B
print("D")
d = D()
#关于继承链的方法和属性
print(issubclass(D,A))#D是否是A的子类
print(D.__bases__) #返回D的基类,即C
print(isinstance(d,B))#d是否是B的实例(对象)
print(d.__class__)#属性,返回d的类型,D类
输出
B
B
D
True
(<class '__main__.C'>,)
True
<class '__main__.D'>
#实现的隐藏
#实现:接口和实现应当分离,实现是设计师不需要了解的部分,例如软件工程师不需要了解半导体连接原理等等
class Universe:
def __init__(self):
self.__privateAttribute = 'I\'m a secret!'#前面两条下划线代表这是私有,隐藏的属性
def __privateMethod(self):#前面两条下划线代表这是隐藏的方法
print("I\'m a hidden method")
def publicMethod(self):#实现用户接口的功能
self.__privateMethod()
print(self.__privateAttribute)
solarsys = Universe()
solarsys.publicMethod()
solarsys.__privateMethod
print(solarsys.__privateAttrivute)
输出
I'm a hidden method
I'm a secret!
Traceback (most recent call last):
File "d:\PARADISE\1.py", line 15, in <module>
solarsys.__privateMethod
AttributeError: 'Universe' object has no attribute '__privateMethod'
#Stock.py
class Stock:
def __init__(self,id = 'N/A',sname = 'N/A',fprice_Before = 0,fprice_current = 0):
self.name = sname
self.price_Before = fprice_Before
self.price_current = fprice_current
self.idnum = id
def get_name(self):
print("name:",self.name)
def get_id(self):
print("id:",self.idnum)
def set_price_Before(self):
self.price_Before = eval(input("请输入前一天的价格:"))
def get_price_Before(self):
print("Bprice:",self.price_Before)
def set_price_current(self):
self.price_current = eval(input("请输入目前的价格:"))
def get_price_current(self):
print("Cprice:",self.price_current)
def getChangePrice(self):
return '{:.1f}%'.format((self.price_current - self.price_Before) / self.price_Before * 100)
def discription(self):
print('{}({}):\n当前价格:{:.2f}元\n昨日价格:{:.2f}元\n价格改变百分比:{}'.format(self.name,self.idnum,\
self.price_current,self.price_Before,self.getChangePrice()))
oneStock = Stock(601318,'中国银行')
oneStock.set_price_Before()
oneStock.set_price_current()
oneStock.discription()
输出
请输入目前的价格:63.21
中国银行(601318):
当前价格:63.21元
昨日价格:64.39元
价格改变百分比:-1.8%
#字符串进阶知识
import math
pi = math.pi
s1 = '你身体里的每一个原子都来自一颗爆炸了的恒星,\
形成你左手的原子可能与右手的来自不同的恒星,\
这是在是我所知物理学中最富诗意的东西,\
你的一切都是星辰'
s2 = 142857
s3 = 0.928512
stext = 'I love this sentence: {} \nand this number: {number:.9f}'.format(s1,number = s3)
print(stext)
#{}内的替代字段如果与当前作用域内的变量名同名,字符串的格式化代码可以简化
print(f'This a mysterious number: {s2},\nbut I love this number more: {s3:.9f}')
#格式说明符举例
print('{num:c}'.format(num = 0x1f60a))#整数按Unicode码转换为相应符号
print("{s:f}".format(s = pi))#定点小数
print("s2:{:g},s3:{:g}".format(s2,s3))#系统自行选择定点小数或科学计数法表示整数/浮点数
print("s2:{:n},s3:{:n}".format(s2,s3))#系统自行选择定点小数或科学计数法表示整数/浮点数,加入数字分隔符
#宽度、精度和分隔符
print('{
{pi:10.3f}} = {pi:10.3f}'.format(pi = pi))#定点小数的宽度为10
print('{
{t:10}} = {i:10}'.format(i = s2))#整数的宽度为10
print('{
{s:.10}} = {s:.10}'.format(s = s1))#字符串的前十个字符,不要落掉点
#符号,对齐,补零
print("{
{pi:010.3f}} = {pi:010.3f}".format(pi = pi))#宽度10,精度3,10前的0表示要补零
print("{
{pi:<10.3f}} = {pi:<10.3f}".format(pi = pi))#宽度10,精度3,居左
print("{
{pi:^10.3f}} = {pi:^10.3f}".format(pi = pi))#宽度10,精度3,居中
print("{
{pi:*>10.3f}} = {pi:*>10.3f}".format(pi = pi))#宽度10,精度3,居右,左边*补齐
print("{
{pi:+10.3f}} = {pi:+10.3f}".format(pi = pi))#宽度10,精度3,显示+号
print("{
{pi:=+10.3f}} = {pi:=+10.3f}".format(pi = pi))#宽度10,精度3,显示+号,=表示
#通过在符号位和数字之间插入填充字符(空格)来满足10位宽度的需求
#center()
#center(目标宽度,填充字符默认空格)
print("'",'center'.center(40),"'")
print('center'.center(40,'*'))
print('center'.ljust(40,'*'))#.ljust()方法左对正
print('center'.rjust(40,'*'))#.rjust()方法左对正
#find()
#find(sub,beg,end)
print(s1.find('星辰',0,len(s1)))
print("Not Found Return:",s1.find("NOT FOUND"))
#replace()
#repalce(old,new,count = -1)
#count表示替换的最大次数,默认值为-1,表示不作限制,全部替换
s4 = 'world is the only thing I care about, I live in the world and finally I will die under the world'
print(s4.replace("world",'uniersity'))
print(s4.replace("world",'uniersity',1))
print(s4.replace("world",'uniersity'))
#split()
#返回一个列表
#rsplit()为从右往左检索(不是返回顺序)
s5 = '1+2+3+4+5'
print(s5.split('+'))
print(s5.rsplit('+'))
#partition(sep)
#按照子串划分字符串,默认从左到右检索,rpartition()为从右到左检索
#返回一个元组
print(s1.partition('形成你左手的原子可能与右手的来自不同的恒星,'))
print(s1.rpartition('形成你左手的原子可能与右手的来自不同的恒星,'))
输出
I love this sentence: 你身体里的每一个原子都来自一颗爆炸了的恒星,形成你左手的原子可能与右手的来自不同的恒星,这是在是我所知物理学中最富诗意的东西,你的一切都是星辰
and this number: 0.928512000
This a mysterious number: 142857,
but I love this number more: 0.928512000
�
3.141593
s2:142857,s3:0.928512
s2:142857,s3:0.928512
{
pi:10.3f} = 3.142
{
t:10} = 142857
{
s:.10} = 你身体里的每一个原子
{
pi:010.3f} = 000003.142
{
pi:<10.3f} = 3.142
{
pi:^10.3f} = 3.142
{
pi:*>10.3f} = *****3.142
{
pi:+10.3f} = +3.142
{
pi:=+10.3f} = + 3.142
' center '
*****************center*****************
center**********************************
**********************************center
69
Not Found Return: -1
uniersity is the only thing I care about, I live in the uniersity and finally I will die under the uniersity
uniersity is the only thing I care about, I live in the world and finally I will die under the world
uniersity is the only thing I care about, I live in the uniersity and finally I will die under the uniersity
['1', '2', '3', '4', '5']
['1', '2', '3', '4', '5']
('你身体里的每一个原子都来自一颗爆炸了的恒星,', '形成你左手的原子可能与右手的来自不同的恒星,', '这是在是我所知物理学中最富诗意的东西,你的一切都是星辰')
('你身体里的每一个原子都来自一颗爆炸了的恒星,', '形成你左手的原子可能与右手的来自不同的恒星,', '这是在是我所知物理学中最富诗意的东西,你的一切都是星辰')
#文件读写
#f.read():从文件中读出全部内容并以字符串形式(文本模式)返回
#f.read(5):从文件读出五个字符
#f.readline() -->str
#f.readlines() -->list
#f.write()写入数据
#f.writeline()写入一行
#fileObject.seek(offset[, whence])
#offset -- 开始的偏移量,也就是代表需要移动偏移的字节数
#whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;
# 0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。
f = open('letter.txt','r',encoding = 'UTF-8')
sflines = f.read()
f.seek(0,0)
flst = f.readlines()
f.seek(0,0)
sfline = f.readline()
print(sflines)
print(sfline)
print(flst)
文件的工作模式
文件模式 | 说明 |
---|---|
“r” | 读模式 |
“w” | 写模式(以“w”或“w+”模式打开文件时,如果文件不存在,会新建一个,如果存在,原来文件的内容会被“截断”) |
“a” | 附加模式(在原文件内容末尾后添加内容) |
“t” | 文本模式 |
“r+” | 既可读又可写,配合seek()可以在期望写入的位置写入内容 |
“w+” | 既可读又可写,但是原来文件的内容会被“截断” |
#文件读写
#文件内容迭代
#逐字符迭代
with open('letter.txt','r',encoding = 'UTF-8') as f:#在with体结束后文件被自动关闭
while True:
char = f.read(1)
if not char:
break
print(char,end = ',')
f.seek(0,0)#注意前面的f
#逐行迭代
for x in f.readlines():
print(x)
f.seek(0,0)
#逐行迭代
for x in f:
print(x)
f.seek(0,0)
#逐行迭代
lines = list(f)
for x in lines:
print(x)
输出
W,h,e,n, ,I, ,s,t,a,n,d, ,b,e,f,o,r,e, ,t,h,e,e, ,a,t, ,t,h,e, ,d,a,y,',s, ,e,n,d,,, ,t,h,o,u, ,s,h,a,l,t, ,s,e,e,
,m,y, ,s,c,a,r,s, ,a,n,d, ,k,n,o,w, ,t,h,a,t, ,I, ,h,a,d, ,m,y, ,w,o,u,n,d,s, ,a,n,d, ,a,l,s,o, ,m,y, ,h,e,a,l,i,
n,g,.,
,当,日,子,完,了,,,我,站,在,你,的,面,前,,, ,你,将,看,到,我,的,疤,痕,,,知,道,我,曾,经,受,伤,,,也,曾,经,痊,愈,。,When I stand before thee at the day's end, thou shalt see my scars and know that I had my wounds and also my healing.
当日子完了,我站在你的面前, 你将看到我的疤痕,知道我曾经受伤,也曾经痊愈。
When I stand before thee at the day's end, thou shalt see my scars and know that I had my wounds and also my healing.
当日子完了,我站在你的面前, 你将看到我的疤痕,知道我曾经受伤,也曾经痊愈。
When I stand before thee at the day's end, thou shalt see my scars and know that I had my wounds and also my healing.
当日子完了,我站在你的面前, 你将看到我的疤痕,知道我曾经受伤,也曾经痊愈。