Python中的推导式
python的推导式包括列表推导式、集合推导式、字典推导式。
一、列表推导式
(一)格式:
[expr for value in collection ifcondition]
如下代码块:
result = []
for value in collection:
if condition:
result.append(expression)
(二)例子
1、list = [Expresion for var in range]
>>> newlist = [x for x in range(1,10)]
>>> newlist
[1, 2, 3, 4, 5, 6, 7, 8, 9]
2 、根据已经list产生新的列表
>>> newlist
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> nlist = [x*x for x in newlist]
>>> nlist
[1, 4, 9, 16, 25, 36, 49, 64, 81]
3、带条件的列表推导式
>>> nlist
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> nl =[x+2 for x in nlist if x>20]
>>> nl
[27, 38, 51, 66, 83]
4、生成二维的列表
例1:
>>> nl
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> nl2 = [[x,x*2] for x in nl if x > 5]
>>> nl2
[[6, 12], [7, 14], [8, 16], [9, 18]]
例2:
>>> a
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> b =[a[i][i] for i in range(len(a))]
>>> b
[1, 5, 9]
例3:求矩阵的和
>>> a
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> b
[[5, 10, 15], [20, 25, 30], [35, 40, 45]]
>>> d = [[a[r][c]+b[r][c] for c in range(3)] for r in range(3)]
>>> d
[[6, 12, 18], [24, 30, 36], [42, 48, 54]]
5、推导式也可调用函数
>>> fruit
[' banana', ' loganberry ', 'passion fruit ']
>>> freshf = [f.strip() for f in fruit]
>>> freshf
['banana', 'loganberry', 'passion fruit']
6、使用多重循环(嵌套)
例1:
>>> t1 = [2, 4, 5]
>>> t2 = [1, 3, 7]
>>> t3 = [x * y for x in t1 for y in t2]
>>> t3
[2, 6, 14, 4, 12, 28, 5, 15, 35]
>>> t4 =[t1[i] * t2[i] for i in range(len(t1))]
>>> t4
[2, 12, 35]
例2:
>>> t1
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
>>> t2 = [j for i in t1 if len(i) > 1 for j in i if j% 2 ==0]
>>> t2
[2, 4, 6, 8]
7、使用紧凑if_else表达式
注意要把if_else看作一个表达式
>>> t1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> t2 = [i if i>5 else 0 for i in t1]
>>> t2
[0, 0, 0, 0, 0, 0, 6, 7, 8, 9]
8、生成元组
求(x,y)其中x是0-5之间的偶数,y是0-5之间的奇数组成的元组列表
>>> a=[(x,y) for x in range(5) if x%2==0 for y in range(5) if y %2==1]
>>> a
[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]
二、字典推导式
1、常用形式
例1
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b = {x:x**2 for x in a if x>5}
>>> b
{6: 36, 7: 49, 8: 64, 9: 81}
例2:
>>> a=[1,2,3]
>>> d = {k:v for k,v in enumerate(a)}
>>> d
{0: 1, 1: 2, 2: 3}
三、集合推导式
合推导式跟列表推导式非常相似,唯一区别在于用{}代替[]。