本章知识小结:
1、tuple元祖()、list列表 [](连接和联合列表,extend的速度比+快)、集合、字典、推导式
2、bisect、哈希化、自动哈希化、[[x for x in tup] for tup in some_tuples]
3、函数、参数(位置蚕食、关键字参数、默认值、*list、**list)
4、匿名函数lambda、柯里化、生成器iter
5、yield惰性返回序列、itertools.groupby(a,b)
6、try-except-else-finally、with open(path) as f:、read、readlines、writelines(strings)
7、with open(path) as f、sys.getdefaultencoding()
1、数据结构和序列 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 import bisectc = [1 ,2 ,2 ,2 ,3 ,4 ,7 ] print (bisect.bisect(c,2 )) print (bisect.bisect(c,5 )) print (bisect.insort(c,6 )) print (c)mapping = dict (zip (range (5 ),reversed (range (5 )))) print (mapping)print (hash ("不可变值" ))d = {} d[tuple ([1 ,2 ,3 ])] = 5 print (d)
2、函数
位置参数、关键字参数(赋值)
命名空间(函数调用时分配内存空间,结束销毁)、作用域、本地函数
没有return返回None、return可以返回多个值
2.1 匿名(Lambda)函数 1 2 3 4 5 6 def apply_to_list (some_list,f ): return [f(x) for x in some_list] ints = [4 ,0 ,1 ,5 ,6 ] print (ints)print (apply_to_list(ints,lambda x:x*2 ))
2.2 柯里化:部分参数应用
专业术语,表示通过部分参数 应用的方式,从已有函数中衍生出新的函数
1 2 3 4 5 6 7 8 9 def add_numbers (x,y ): return x+y add_five = lambda y:add_numbers(5 ,y) print (add_five(4 ))from functools import partialadd_five = partial(add_numbers,5 )
2.3 生成器(迭代器iter) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 some_dict = {'a' :1 ,'b' :2 ,'c' :3 } dict_iterator = iter (some_dict) print (dict_iterator)print (list (dict_iterator))def squares (n=10 ): print (f"将要输出{n} 个数" ) for i in range (1 ,n+1 ): yield i ** 2 gen = squares() print (gen)for x in gen: print (x,end=' ' ) gen = (x**2 for x in range (10 )) print (list (gen))import itertoolsfirst_letter = lambda x:x[0 ] names = ['Alan' ,'Adam' ,'Wex' ,'Will' ,'Albert' ,'Steven' ] names.sort() for letter , names in itertools.groupby(names,first_letter): print (letter,list (names))
2.4 错误和异常处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 def attempt_float (x ): try : return float (x) except (TypeError, ValueError): return x print (attempt_float(2 ),attempt_float('string' ),attempt_float((1 ,2 )))f = open ( path ,'w' ) try : write_to_file(f) except : print ('Failed' ) else : print ('Succeeded' ) finally : f.close()
3、文件和操作系统
打开关闭文件
1 2 3 4 5 6 7 8 9 path = 'a.txt' f = open (path) for line in f: pass f.close() with open (path) as f : pass
用sys模块检查文件编码
1 2 import sysprint (sys.getdefaultencoding())
字节与Unicode (默认是Unicode)
1 2 3 4 prase = "哈哈哈哈哈" val = prase.encode('utf-8' ) print (val)print (val.decode('utf-8' ))