第二天 Python3.4.2 里面的字典 列表解析等等
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第二天 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) [[email protected] ~]# 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) [[email protected] ~]# 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)]
以上是关于第二天 Python3.4.2 里面的字典 列表解析等等的主要内容,如果未能解决你的问题,请参考以下文章