列表推导式语法:
[表达式 for 变量 in 序列或迭代对象]
列表推导式在逻辑上相当于一个循环,
如:
>>>alist = [x * x for x in range(10)]
相当于:
>>>alist = []
>>>for x in range(10):
alist.append(x*x)
也等价于:
>>>alist=list(map(lambda x: x*x,range(10)))
1、使用列表推导式实现嵌套列表的平铺
>>>vec=[[1,2,3],[4,5,6],[7,8,9]]
>>>[num for elem in vec for num in elem]
[1,2,3,4,5,6,7,8,9]
等价于:
>>>vec=[[1,2,3],[4,5,6],[7,8,9]]
>>>result=[]
>>>for elem in vec:
for num in elem:
result.append(num)
>>>result
[1,2,3,4,5,6,7,8,9]
2、过滤不符合条件的元素
列出当前文件夹下所有的 .py 文件
>>>import os
>>>[filename for filename in os.listdir(‘.’) if filename.endswith(‘.py’)]
从列表中选择符合条件的元素组成新的列表:
>>>alist = [ -1, -4,6, 7.5, -2.3, 9, -11 ]
>>>[i for i in alist if i>0]
[ 6, 7.5, 9]
>>>scores = {“zhang shan”:45 , “li si”:78 , “wang wu”:40}
>>>highest = max(scores.values()) #求最高分
>>>lowest = min(scores.values()) #求最低分
>>>average = sum(scores.values())/len(scores) #求平均分
>>>highestPerson = [name for name, score in scores.items() if score == highest]
>>>highestPerson
[‘li si’]
3、实现多序列元素的任意组合
>>>[(x,y) for x in (1,2,3) for y in (3,1,4) if x!=y]
[(1,3), (1,4), (2,3), (2,1), (2,4), (3,1), (3,4)]
4、实现矩阵转置
>>>matrix = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]
>>>[[row[i] for row in matrix] for i in range(4)]
[[1,5,9], [2,6,10], [3,7,11], [4,8,12]]
相当于:
>>>list(map(list,zip(*matrix)))
[[1,5,9], [2,6,10], [3,7,11], [4,8,12]]
5、列表推导式中可以使用函数或复杂表达式
>>>def f(v):
if v%2 == 0:
v = v**2
else:
v = v+1
return v
>>>print([f(v) for v in [2,3,4,-1] if v>0])
[4,4,16]
>>>print([v**2 if v%2==0 else v+1 for v in [2,3,4,-1] if v>0])
[4,4,16]
6、列表推导式支持文件对象的迭代
>>>fp = open(‘c:\install.log’,’r’)
>>>print([line for line in fp])
>>>fp.close()
7、列表推导式生成 100 以内的素数
>>>[ p for p in range(2,100) if 0 not in [p%d for d in range(2,int(sqrt(p))+1)]]
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,51,67,71,73,79,83,89,97]