AdSense

網頁

2025/6/15

Python list comprehension語法

Python list comprehension語法如下。


[表達式 for 元素 in 集合 if 條件]

閱讀順序是先看for 元素 in 集合loop,然後把集合的元素帶到if 條件,最後將滿足if條件的元素帶到表達式

例如下面loop range(5)產生的[0, 1, 2, 3, 4]中的每個元素x,若x % 2 == 0,也就是x為偶數的話才取出,然後將x * 2並放到新的list變數r中。

r = [x * 2 for x in range(5) if x % 2 == 0]
print(r) # [0, 4, 8]

下面範例比較一般for loop寫法和list comprehension語法。

r = []
nums = [1, 2, 3, 4, 5] # nums is a list
for n in nums:
    r.append(n * 3)
print(r) # [3, 6, 9, 12, 15]

r = [n * 3 for n in nums] # list comprehensions, nums中的每個元素乘以3
print(r) # [3, 6, 9, 12, 15]

#--------------------------------------------------------------------------------------
r = []
for n in nums:
    if (n % 2 == 0):
        r.append(n)
print(r) #[2, 4]

r = [n for n in nums if (n % 2) == 0] # list comprehensions, 取得nums中元素為偶數的部分
print(r) # [2, 4]


沒有留言:

AdSense