作者: Sam(甄峰)
sam_code@hotmail.com
Python 有个语法糖(syntactic sugar)叫做list comprehension(列表推导式).
主要利用一个已知List推导新的List。
语法规范为:
out_list = [out_express for out_express in input_list if
out_express_condition]
它主要用来对已知List进行过滤,转换或者组合,产生新的List。
其中,if那一块是可选的。
例1:
list_data = [1,2,3,4,5,6,7,8,9,10]
list_J = [dat for dat in list_data if (dat%2)== 0]
print(list_J)
结果是:
[2, 4, 6, 8, 10]
例2:
没有if 部分的例子:
list_sq = [x*x for x in list_data]
print(list_sq)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
例3:
复杂的用法,两层for循环:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
flattened = [i
for row in matrix
for i in row
]
print(flattened)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
例4:
l_1=[2,4,6]
l_2=[1,3,5]
add = [vec[i]+vec2[i] for i in range(len(vec))]
print(add)
结果:
[3, 7, 11]