需求
統計列表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 中的列表生成器