列表生成式

Python 工具箱

Hugo Bowne-Anderson

Data Scientist at DataCamp

用 for 迴圈建立列表

nums = [12, 8, 21, 3, 16]

new_nums = []
for num in nums: new_nums.append(num + 1)
print(new_nums)
[13, 9, 22, 4, 17]
Python 工具箱

列表生成式範例

nums = [12, 8, 21, 3, 16]
new_nums = [num + 1 for num in nums]

print(new_nums)
[13, 9, 22, 4, 17]
Python 工具箱

for 迴圈與列表生成式語法

new_nums = [num + 1 for num in nums]
for num in nums:
    new_nums.append(num + 1)

print(new_nums)
[13, 9, 22, 4, 17]
Python 工具箱

搭配 range() 的列表生成式

result = [num for num in range(11)]

print(result)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Python 工具箱

列表生成式

  • 將建立列表的 for 迴圈濃縮成一行
  • 組成要素
    • 可疊代物件
    • 疊代變數(代表可疊代物件的成員)
    • 輸出運算式
Python 工具箱

巢狀迴圈(1)

pairs_1 = []

for num1 in range(0, 2): for num2 in range(6, 8): pairs_1.append((num1, num2))
print(pairs_1)
[(0, 6), (0, 7), (1, 6), (1, 7)]
  • 用列表生成式要怎麼寫?
Python 工具箱

巢狀迴圈(2)

pairs_2 = [(num1, num2) for num1 in range(0, 2) for num2 in range(6, 8)]

print(pairs_2)
[(0, 6), (0, 7), (1, 6), (1, 7)]
  • 取捨:可讀性
Python 工具箱

一起來練習吧!

Python 工具箱

Preparing Video For Download...