Overview

從一個資料序列建立另一個新的資料序列的結構體。

List Comprehension 串列推導式

a = [1,2,3,4,5]
gen_exp = (element for element in a)  # <generator object <genexpr> at 0x0000017378B98DC8>
list(gen_exp)  # [1, 2, 3, 4, 5]
[element for element in a]  # [1, 2, 3, 4, 5]
[element for element in a if element % 2 == 1]  # [1, 3, 5]
[element**2 for element in a if element % 2 == 1]  # [1, 9, 25]

Dict Comprehension 字典推導式

a = {'a':10, 'b':20, 'c':30}
{v: k for k, v in a.items()}
# {10: 'a', 20: 'b', 30: 'c'}

a = {'a': 10, 'b': 20, 'A': 30, 'Z': 40}
{k.lower(): a.get(k.lower(), 0) + a.get(k.upper(), 0) for k in a.keys() if k.lower() in ['a', 'b']}
# {'a': 40, 'b': 60}

Set Comprehension 集合推導式

a = {1,2,3,4,5}
{x**2 for x in a}
# {1, 4, 9, 16, 25}