進階推導式

Python 工具箱

Hugo Bowne-Anderson

Data Scientist at DataCamp

推導式中的條件

  • 針對可疊代物件加上條件
    [num ** 2 for num in range(10) if num % 2 == 0]
    
[0, 4, 16, 36, 64]
  • Python 文件中 % 運算子的說明:%(取餘數)會回傳第一個運算元除以第二個運算元的餘數。
5 % 2
1
6 % 2
0
Python 工具箱

推導式中的條件

  • 針對輸出運算式加上條件
[num ** 2 if num % 2 == 0 else 0 for num in range(10)]
[0, 0, 4, 0, 16, 0, 36, 0, 64, 0]
Python 工具箱

字典推導式

  • 建立字典
  • 使用大括號 {},不要用中括號 []
pos_neg = {num: -num for num in range(9)}

print(pos_neg)
{0: 0, 1: -1, 2: -2, 3: -3, 4: -4, 5: -5, 6: -6, 7: -7, 8: -8}
print(type(pos_neg))
<class 'dict'>
Python 工具箱

一起來練習吧!

Python 工具箱

Preparing Video For Download...