第二天 Python3.4.2 里面的字典 列表解析等等
一.字典
1.字典是一种无序集合
2.字典是一种KV结构
3.value可以是任何对象
4.key必须是可以hash对象
二.列表解析
1.列表解析是python重要的语法课
2.列表解析的速度比for in 迭代快
例子1:
In [1]: lst = list(range(10)) In [2]: lst Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
列表解析: In [3]: [x+1 for x in lst] Out[3]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
麻烦的写法:
In [4]: l = [] In [5]: for x in lst: ...: l.append(x+1) ...: In [6]: l Out[6]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
在执行效率上看:
(test_3.4.2) [root@Minion1 ~]# vim test_time.py import timeit lst = range(10) def fn1(): [x+1 for x in lst] def fn2(): l = [] for x in lst: l.append(x+1) print (timeit.timeit('[x+1 for x in range(10)]')) print (timeit.timeit(''' l = [] for x in range(10): l.append(x+1) '''))
其结果:
(test_3.4.2) [root@Minion1 ~]# python test_time.py
2.363238713995088
2.931454276003933
明显的列表解析需要的时间快一些。
3.字典解析
ret = {exprk:exprv for item in iterator}
等价于:
ret = dict {}
for item in iterator:
ret.update({exprk,exprv})
4.带条件的列表解析:
In [7]: lst Out[7]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [8]: [x+1 for x in lst if x % 2 == 0] Out[8]: [1, 3, 5, 7, 9] 相当于:
In [12]: l=[] In [13]: for x in lst: ....: if x % 2 ==0: ....: l.append(x+1) ....: In [14]: print (l) [1, 3, 5, 7, 9]
4.1 带多个条件的列表解析:
In [15]: [x+1 for x in lst if x % 2 == 0 if x >2] Out[15]: [5, 7, 9] In [16]: l = [] In [17]: for x in lst: ....: if x % 2 ==0 and x >2: ....: l.append(x+1) ....: print (l) ....: [5, 7, 9]
4.1 笛卡尔积
ret = [expression for x in x for y in y]
In [18]: l1=[1,3,5,7,9] In [19]: l2=[0,2,4,6,8] In [20]: [(x,y) for x in l1 for y in l2] Out[20]: [(1, 0), (1, 2), (1, 4), (1, 6), (1, 8), (3, 0), (3, 2), (3, 4), (3, 6), (3, 8), (5, 0), (5, 2), (5, 4), (5, 6), (5, 8), (7, 0), (7, 2), (7, 4), (7, 6), (7, 8), (9, 0), (9, 2), (9, 4), (9, 6), (9, 8)]
5.集合的解析
ret = {expression for item in iterator}
等价于:
ret = set ()
for item in iterator:
ret.add(expression)
In [21]: s = {1,3,5} In [22]: {x+1 for x in s} Out[22]: {2, 4, 6} In [23]: {x+1 for x in range(10)} Out[23]: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} In [24]: {x+1 for x in{2,2,2,2,2}} Out[24]: {3} #因为集合不能重复,所以只有一个3
6.生成字典
In [29]: l1
Out[29]: [1, 3, 5, 7, 9]
In [30]: l2
Out[30]: [0, 2, 4, 6, 8]
In [28]: {x:y for x in l1 for y in l2} Out[28]: {1: 8, 3: 8, 5: 8, 7: 8, 9: 8}
y 其实也是赋值过 0,2,4,6 只是最后输出的时候才把8付到上面 生成一个新的字典,是这样理解。
In [31]: {x:y for x in l2 for y in l1} Out[31]: {0: 9, 2: 9, 4: 9, 6: 9, 8: 9} ----------------------------- In [39]: l1=[1,2,3] In [40]: l2=['a','b','c'] In [41]: l3=[(x,y) for x in l1 for y in l2] In [42]: l3 Out[42]: [(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c')]
总结: 集合解析 和 字典解析 都是用大括号。
正常字体