快轉到主要內容
  1. posts/

[Python] 列表推導式 List Comprehension

·
Python
目錄

簡介
#

List Comprehension 提供了一個簡短的語法讓我們可以透過一個已經存在的 list 創建一個新的 list。

假設想要新增一個 list,而這個 list 只需要 fruits 中含有字元 'a' 的元素。

在沒有 List Comprehension 的情況下程式可能會這樣子寫:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]  
newlist = []  
  
for x in fruits:  
  if "a" in x:  
    newlist.append(x)  
  
print(newlist)

如果使用了 List Comprehension,就可以只用一行程式碼做到和上面程式碼相同的事情:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]  
  
newlist = [x for x in fruits if "a" in x]  
  
print(newlist)

語法
#

newlist = [expression for item in iterable if condition == True]

Referance
#

Python - List Comprehension