python進階-lambda和列表生成器


需求

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM