推导式是python的一个特性,可以让你很方便的生成一些数据
推导式在python中主要有以下三种应用
-
list 推导
>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
加上一个条件,只要偶数
>>> [i for i in range(20) if i % 2 == 0]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
将两个列表组合成一个
>>> nums = [1, 2, 3, 4]
>>> fruit = ["Apples", "Peaches", "Pears", "Bananas"]
>>> [(i, f) for i in nums for f in fruit]
[(1, 'Apples'), (1, 'Peaches'), (1, 'Pears'), (1, 'Bananas'),
(2, 'Apples'), (2, 'Peaches'), (2, 'Pears'), (2, 'Bananas'),
(3, 'Apples'), (3, 'Peaches'), (3, 'Pears'), (3, 'Bananas'),
(4, 'Apples'), (4, 'Peaches'), (4, 'Pears'), (4, 'Bananas')]
同理,可以加上筛选条件
>>> [(i, f) for i in nums for f in fruit if f[0] == "P"]
[(1, 'Peaches'), (1, 'Pears'),
(2, 'Peaches'), (2, 'Pears'),
(3, 'Peaches'), (3, 'Pears'),
(4, 'Peaches'), (4, 'Pears')]
PS:如果把这里把 [ ] 改成 (),生成的则是generator
>>> g = (i for i in range(10))
>>> type(g)
<class 'generator'>
-
dict 推导
构造一个简单的dict
>>> {i : chr(65+i) for i in range(4)}
{0: 'A', 1: 'B', 2: 'C', 3: 'D'}
交换 key 和 value 的位置
>>> d = {0: 'A', 1: 'B', 2: 'C', 3: 'D'}
>>> {v : k for k, v in d.items()}
{'A': 0, 'B': 1, 'C': 2, 'D': 3}
合并相同key的值
>>> d = {'a': 1, 'b': 2, 'A': 9, 'z': 8}
>>> {k.lower(): d.get(k.lower(), 0) + d.get(k.upper(), 0) for k in d.keys()}
{'a': 10, 'b': 2, 'z': 8}
-
set 推导
>>> {x * x for x in [1, 1, 2]}
{1, 4}
觉得有用的老铁点个赞再走呗!