python学习笔记之列表解析
列表解析
列表解析是一种能快速生成列表的方法,在对元素的迭代上速度快于for循环
1
| ret = [expression for item in iterator]
|
等同于:
1 2 3
| ret = [] for item in iterator: ret.append(expression)
|
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
上边的列表解析等价于下边的for循环,但速度上列表解析要快:
1 2 3 4
| ret = [] for x in lst1: ret.append(x + 1) ret
|
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1
| [x + 1 for x in lst1 if x%2 == 0]
|
[1, 3, 5, 7, 9]
等同于下边:
1 2 3 4 5
| ret = [] for x in lst1: if x % 2 == 0: ret.append(x + 1) ret
|
[1, 3, 5, 7, 9]
1
| [x + 1 for x in lst1 if x%2 == 0 if x > 2]
|
[5, 7, 9]
等同于下边:
1 2 3 4 5
| ret = [] for x in lst1: if x % 2 == 0 and x > 2: ret.append(x + 1) ret
|
[5, 7, 9]
操作多个列表
1 2 3
| l1 = [1,3,5] l2 = [2,4,6] [(x,y) for x in l1 for y in l2]
|
[(1, 2), (1, 4), (1, 6), (3, 2), (3, 4), (3, 6), (5, 2), (5, 4), (5, 6)]
等价于:
1 2 3 4 5
| ret = [] for x in l1: for y in l2: ret.append((x,y)) ret
|
[(1, 2), (1, 4), (1, 6), (3, 2), (3, 4), (3, 6), (5, 2), (5, 4), (5, 6)]
列表解析用于集合时只需要把’[]‘修改成’{}'即可,语法不会发生改变,但集合有一个特性,就是会去掉列表中的重复数据。
1 2
| s = {1,3,5,7} {x + 1 for x in s}
|
{2, 4, 6, 8}
1 2
| l3 = [1,3,5,7,5,3] {x + 1 for x in l3}
|
{2, 4, 6, 8}
1 2 3
| l4 = ['a','b','c'] l5 = [1,2,3] {k:v for k in l4 for v in l5}
|
{'a': 3, 'b': 3, 'c': 3}
1
| [(k,v) for k in l4 for v in l5]
|
[('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('b', 3),
('c', 1),
('c', 2),
('c', 3)]
从上边的两个例子中可看出:生成字典与生成列表时是有些区别的,在对多个列表操作生成字典时,字典的key是第一个for词句中的各元素,而v是第二个for词句中的最后一个元素。而生成一个列表时返回的是一个笛卡尔乘积。
一个元素是元组的列表,可利用列表解析生成一个字典,如下:
1
| l5 = [('a',1),('b',2),('c',3)]
|
{'a': 1, 'b': 2, 'c': 3}