容器
列表
1 # 容器 2 li=[1,2,3,‘abc‘,4.5,[2,3,4],{1:‘one‘}] 3 4 print(len(li)) 5 6 print(li[0]) 7 print(li[-1]) #{1:‘one‘} 8 9 li=[1,2,3] 10 li.append(‘a‘) 11 li.append(‘b‘) 12 print(li) 13 li.append([4,5,6]) #[1, 2, 3, ‘a‘, ‘b‘, [4, 5, 6]] 14 print(li) 15 li=[1,2,3] 16 li.extend([4,5,6]) #[1, 2, 3, 4, 5, 6] 17 print(li) 18 19 li=[1,2,3,4,5] 20 li.pop() #[1, 2, 3, 4] 21 print(li) 22 del(li[0]) 23 del(li[1]) 24 print(li)#[2, 4] 25 print(‘‘) 26 27 li=[] 28 if not li: 29 print(‘empty‘) 30 else: 31 print(‘not empty‘) 32 print(‘‘)
#遍历 li=[1,2,3] for j in li: print(j) for i in range(len(li)): print(li[i])
元组
#元组:不能写,只能读 t=(1,2,3) print(t)
字典:key/value
1 d={‘a‘:1,2:‘b‘,‘c‘:3,4:‘d‘} 2 print(len(d)) 3 4 d[‘a‘]=100 5 d[4]=‘dd‘ 6 print(d) 7 print(‘‘) 8 9 #添加元素 10 d[‘e‘]=5 11 d[6]=‘f‘ 12 print(d) 13 print(‘‘) 14 15 #删除元素 16 d={‘a‘:1,2:‘b‘,‘c‘:3,4:‘d‘} 17 del(d[‘a‘]) 18 del(d[2]) 19 print(d) 20 print(‘‘) 21 22 #判断key是否存在 23 d={‘a‘:1,2:‘b‘,‘c‘:3,4:‘d‘} 24 if ‘a‘ in d: 25 print(‘a in d‘) 26 if 2 in d: 27 print(‘2 in d‘) 28 if not (‘x‘ in d): 29 print(‘x not in d‘) 30 print(‘‘) 31 32 #判断字典是否为空 33 d={} 34 if not d: 35 print(‘d is empty‘) 36 print(‘‘) 37 38 #遍历 39 d={‘a‘:1,2:‘b‘,‘c‘:3,4:‘d‘} 40 for k in d.keys(): 41 print(str(k)+‘:‘+str(d[k])) 42 for k,v in d.items(): 43 print(str(k)+":"+str(v))
集合:没有重复元素
1 s_a=set([1,2,3,4,5]) 2 s_b=set([1,1,2,2,3,4,5]) #{1, 2, 3, 4, 5} 3 print(s_a) 4 print(s_b) 5 print(‘‘) 6 7 print(len(s_a)) 8 9 s_a.add(6) 10 s_a.add(6) 11 s_a.update([5,6,7,8,9]) #{1, 2, 3, 4, 5, 6, 7, 8, 9} 12 print(s_a) 13 print(‘‘) 14 15 s_a.remove(8) 16 s_a.remove(9) 17 print(s_a) 18 print(‘‘) 19 20 #判断元素是否存在 21 print(1 in s_a) #True 22 print(10 in s_a) 23 print(‘‘) 24 25 #判断集合是否为空 26 s_a=set([]) 27 if not s_a: 28 print(‘set is empty‘) 29 else: 30 print(‘set is not empty‘) 31 print(‘‘) 32 33 #遍历 34 s_a=set([1,2,3,4,5]) 35 for i in s_a: 36 print(i) 37 print(‘‘) 38 39 #集合操作 40 s_a=set([1,2,3,4,5]) 41 s_b=set([4,5,6,7,8]) 42 #并集 43 print(s_a | s_b) #{1, 2, 3, 4, 5, 6, 7, 8} 44 print(s_a.union(s_b)) 45 #交集 46 print(s_a & s_b)#{4, 5} 47 print(s_a.intersection(s_b)) 48 #差集 49 print(s_a - s_b) #{1, 2, 3} 50 print(s_a.difference(s_b)) 51 #对称差 52 print(s_a ^ s_b) #{1, 2, 3, 6, 7, 8} 53 print((s_a | s_b)-(s_a&s_b)) 54 print(s_a.symmetric_difference(s_b))
字符串:不可变
s=‘abcdefg‘ li=list(s) li[4]=‘E‘ li[5]=‘F‘ print(li) s=‘‘.join(li) #[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘E‘, ‘F‘, ‘g‘] print(s) print(‘‘)
切片:开区间[):<= x <
1 li=[0,1,2,3,4,5,6,7,8,9,10] 2 print(li[2:5]) #[2, 3, 4] 3 print(li[:4]) #[0, 1, 2, 3] 4 print(li[5:]) #[5, 6, 7, 8, 9, 10] 5 print(li[:]) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 6 print(li[0:6:2]) #[0, 2, 4] 7 print(li[3::2]) #[3, 5, 7, 9] 8 print(‘‘) 9 10 #负数索引和step 11 print(li[::-1]) #[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] 12 print(li[::-2]) #[10, 8, 6, 4, 2, 0] 13 print(li[-6:-1:1])#[5, 6, 7, 8, 9] 14 print(li[-1::-1]) #[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
生成器:计算延迟,什么时候用到才计算这个值
面向对象
廖雪峰的教程
基础
1 class MyClass: 2 def __init__(self,val):#初始化函数,不是构造函数 3 self.val=val 4 5 def display(self,s): 6 print(‘%s:%d‘ % (s,self.val)) 7 8 m=MyClass(100) 9 print(m.val) 10 m.display(‘hello‘) 11 print(‘‘) 12 13 m2=m 14 print(id(m)) #52343408 15 print(id(m2))#52343408 16 17 fn=m.display 18 fn(‘hey‘)
继承,多态
1 class Base: 2 pass 3 class MyClass(Base): 4 def run(self): 5 print(‘MyClass run‘) 6 7 class MyClass2(Base): 8 def run(self): 9 print(‘MyClass2 run‘) 10 11 m=MyClass() 12 print(isinstance(m,MyClass)) 13 print(issubclass(MyClass2,Base)) 14 print(‘‘) 15 16 #多态 17 m2=MyClass2() 18 m.run() 19 m2.run() 20 21 def duck(d): 22 d.run() 23 class Man: 24 def run(self): 25 print(‘man run‘) 26 27 class Monkey: 28 def run(self): 29 print(‘monkey run‘) 30 31 duck(Man()) 32 duck(Monkey())
异常处理
1 import traceback 2 3 try: 4 print(‘try...‘) 5 r=10/0 6 except ZeroDivisionError as e: 7 print(‘ZeroDivisionError:‘,e) 8 print(traceback.print_exc()) 9 finally: 10 print(‘finally...‘) 11 12 ‘‘‘ 13 结果: 14 Traceback (most recent call last): 15 try... 16 File "D:/pythonproject/test/base/01container.py", line 5, in <module> 17 r=10/0 18 ZeroDivisionError: division by zero 19 ZeroDivisionError: division by zero 20 None 21 finally... 22 ‘‘‘
文件读写
#字符读写 #二进制读写 import struct with open(‘sample.bmp‘,‘rb‘) as f: header=struct.unpack(‘<2c6I2H‘,f.read(30)) print(header)
json处理
1 import json 2 3 d={‘ptyhon‘:100,‘c++‘:70,‘basix‘:60,‘others‘:{‘c‘:65,‘java‘:50}} 4 jtxt=json.dumps(d) #字典转成json {"ptyhon": 100, "c++": 70, "basix": 60, "others": {"c": 65, "java": 50}} 5 dd=json.loads(jtxt) #json转成字典 {‘ptyhon‘: 100, ‘c++‘: 70, ‘basix‘: 60, ‘others‘: {‘c‘: 65, ‘java‘: 50}} 6 print(jtxt) 7 print(dd) 8 print(‘‘) 9 10 #非dict对象如何用json序列化? 11 class Student: 12 def __init__(self,name,age,score): 13 self.name=name 14 self.age=age 15 self.score=score 16 17 def __str__(self): 18 return ‘%s:%d,%d‘ % (self.name,self.age,self.score) 19 20 s=Student(‘Tome‘,15,85) 21 print(s) 22 print(s.__dict__) #{‘name‘: ‘Tome‘, ‘age‘: 15, ‘score‘: 85} 23 #方法1 24 jtxt=json.dumps(s,default=lambda obj:obj.__dict__) 25 print(jtxt) #{‘name‘: ‘Tome‘, ‘age‘: 15, ‘score‘: 85} 26 def d2s(d): 27 return Student(d[‘name‘],d[‘age‘],d[‘score‘]) 28 print(json.loads(jtxt, object_hook =d2s)) #Tome:15,85 29 30 #方法2 31 def s2d(s): 32 return s.__dict__ 33 jtxt=json.dumps(s,default=s2d) 34 print(jtxt)