在 Python 中有個好東西 Comprehension,這麼說好了如果我們有個 list 我們想要整理產生另一個 list 就可以使用 Comprehension,我們先簡單把 [1, 2, 3, 4, 5]
變成 [2, 4, 6, 8, 10]
一般來說會這樣處理。
dataList = [1, 2, 3, 4, 5]
result = []
for i in dataList:
result.append(i * 2)
print(result) # [2, 4, 6, 8, 10]
那如果使用了 Comprehension 會變成這樣,非常短。
dataList = [1, 2, 3, 4, 5]
result = [i * 2 for dataList]
print(result) # [2, 4, 6, 8, 10]
聰明如你一定也想到這個範例也可以使用 lambda 來完成
dataList = [1, 2, 3, 4, 5]
result = list(map(lambda item: item * 2, dataList))
print(result) # [2, 4, 6, 8, 10]
那如同 lambda,Comprehension 也能使用簡單的條件。
dataList = [1, 2, 3, 4, 5, 6, 7, 8 , 9, 10]
result = [i * 2 for dataList if i % 2 == 0]
print(result) # [2, 4, 6, 8, 10]
最後來看 Comprehension 語法,Comprehension 可以有三種回傳型態 Dictionary、Generator 三種用法都雷同。
List Comprehension
result = [expression for item in iterable if condition == True]
範例
dataList = [1, 2, 3, 4, 5, 6, 7, 8 , 9, 10]
result = [i * 2 for dataList if i % 2 == 0]
print(result) # [2, 4, 6, 8, 10]
Dictionary Comprehension
result = {expression for item in iterable if condition == True}
範例
dataDict = {
"a": 1,
"b": 2,
"c": 3,
}
dict = {key: value * 2 for key, value in dataDict.items()}
print(dict) # {'a': 2, 'b': 4, 'c': 6}
Generator Comprehension
result = (expression for item in iterable if condition == True)
範例
dataList = [1, 2, 3, 4, 5, 6, 7, 8 , 9, 10]
result = (i * 2 for dataList if i % 2 == 0)
print(result) # <generator object <genexpr> at 0x7fc18d079a98>
print(list(result)) # [2, 4, 6, 8, 10]