1. 程式人生 > >04python 中的各種推導式(python函數)

04python 中的各種推導式(python函數)

pytho err col output key tor 元組 註意 功能

列表推導式與生成器表達式

print([i for i in range(10)])        # 列表推導式

g = (i for i in range(10))           # 生成器表達式
print(g)                             # 打印的結果為生成器   

print([i for i in g])                # 再次調用列表解析

>>>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<generator object <genexpr> at 0x0000006E50CBED58>
[0, 
1, 2, 3, 4, 5, 6, 7, 8, 9]

列表推導式的補充:加上條件

ret = [i for i in range(30) if i % 3 == 0]
print(ret)

>>>[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

多重嵌套

>>> names = [[‘Tom‘, ‘Billy‘, ‘Jefferson‘, ‘Andrew‘, ‘Wesley‘, ‘Steven‘, ‘Joe‘],
[‘Alice‘, ‘Jill‘, ‘Ana‘, ‘Wendy‘, ‘Jennifer‘, ‘Sherry‘, ‘Eva‘]]

>>> print([name for lst in names for name in lst if name.count(‘e‘) >= 2])
[‘Jefferson‘, ‘Wesley‘, ‘Steven‘, ‘Jennifer‘]

字典推導式

>>> dic = {k1: v1, k2: v2, k3: v3}
>>> {v1: k1 for k1, v1 in dic.items()}
{v1: k1, v2: k2, v3: k3}

字典推導式值得註意的地方

>>> {key:value for key in "ABC" for value in range(1,10)}
{A: 9, B: 9, C: 9}

元組推導式

自帶去重功能

squared = {x**2 for x in [1, -1, 2]}
print(squared)
# Output: set([1, 4])

>>>(1, 4)

04python 中的各種推導式(python函數)