一行寫完for loop和if statement(List Comprehensions)

腫魔沒人留言?快點下去搶頭香啊!

參考資料:Python PEP 202 — List Comprehensions

List Comprehensions

如果資料是

>>> nums = [1, 2, 3, 4]
>>> fruit = ["Apples", "Peaches", "Pears", "Bananas"]

可以寫一個for loop

>>> print 

也可以用nested for loop

>>> print [(i, f) for i in nums for f in fruit]
#這裡要注意(i, f)的括號不要漏掉

甚至還可以加上if statement

>>> print [(i, f) for i in nums for f in fruit if f[0] == "P" if i%2 == 1]

不過這樣真的會比較好閱讀嗎?以最後的例子來說,一般寫法是

# print [(i, f) for i in nums for f in fruit if f[0] == "P" if i%2 == 1]
>>> for i in nums:
>>>     for f in fruit:
>>>         if f[0] == "P" and i%2 == 1:
>>>             print(i,f)
#如果是python3, print要加括號

不過要注意的是,一行for loop的寫法是list comprehension,資料是存成list,資料的取用上就必須以list的data structure進行(可參考5. Data Structures),而非個別的variable。

0 0 vote
Article Rating
訂閱(Subscribe)
來自於(Notify of)
0 Comments
Inline Feedbacks
View all comments