需求
统计列表a中所有大于5的元素
普通写法
a=[1,3,4,5,6,9]
temp=[]
for i in a:
if i >5:
temp.append(i)
print(temp)
[6, 9]
进阶
lambda写法
filter()是python的内置方法,对序列中的元素进行筛选,最终获取符合条件的序列
temp=filter(lambda i:i>5,a)
print(list(temp))
[6, 9]
列表生成器写法
temp=[i for i in a if i>5]
print(temp)
[6, 9]
参考文档:
python 中的列表生成器