這篇文章是閱讀Asabeneh的30 Days Of Python: Day 13 - List Comprehension後的學習筆記與心得。
關於列表推導式 - Wikipedia上的詳細名詞解釋
根據30 Days Of Python內的說明,Python的列表推導式就是一種精簡化的清單(list)建立方法:
# 語法
[i for i in iterable if expression]
這個運作起來,一種模式是像Array.map(i => i)
:
squared_numbers = [i * i for i in range(11)]
print(squared_numbers)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
for
前面的表達式代表回傳值也可以用來改變資料結構:
week = {
"sunday": 0,
"monday": 1,
"tuesday": 2,
"wednesday": 3,
"thursday": 4,
"friday": 5,
"saturday": 6
}
week_list = [
{"id": value, "name": key.capitalize()}
for key, value
in week.items()
]
print(week_list)
"""
[
{'id': 0, 'name': 'Sunday'},
{'id': 1, 'name': 'Monday'},
{'id': 2, 'name': 'Tuesday'},
{'id': 3, 'name': 'Wednesday'},
{'id': 4, 'name': 'Thursday'},
{'id': 5, 'name': 'Friday'},
{'id': 6, 'name': 'Saturday'}
]
"""
也能再加上if
在mapping中加入條件,類似JS中的Array.filter(i => condition)
:
even_numbers = [i for i in range(11) if i % 2 == 0]
odd_numbers = [i for i in range(11) if i % 2 != 0]
print(even_numbers) # [0, 2, 4, 6, 8, 10]
print(odd_numbers) # [1, 3, 5, 7, 9]
另一種運作的方式類似兩個for
迴圈,可以用來攤平(flatten)陣列,也就是Python中的List物件:
原文中這個例子寫:"Flattening a three dimensional array"
但應該是二維陣列(two-dimensional array) -- 參考這篇文章的說明
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = [ number for row in list_of_lists for number in row]
print(flattened_list) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
如果用兩個for
迴圈來做的話會是這個樣子:
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = list()
for row in list_of_lists:
for number in row:
flattened_list.append(number)
print(flattened_list)
使用lambda
關鍵字,類似JavaScript的匿名函式(anonymous function),可以接收多個參數,但回傳的部分必須是一個表達式(expression):
語法: variable = lambda [parameter_list] : expression
square = lambda num : num ** 2
print(square(3)) # 9
寫成函式是長這個樣子:
def square(num): return num ** 2
print(square(3)) # 9
另一個用例是在函式中回傳Lambda函式:
def power(x): return lambda n : x ** n
cube = power(2)(3)
print(cube) # 8