1. 程式人生 > >[推導式] 一招理解python列表/字典/集合推導式

[推導式] 一招理解python列表/字典/集合推導式

1. 簡述

  推導式可以用一行程式碼優雅地代替多行程式碼,相當於把多層for迴圈移到一行。

2. 詳解

  先看下錶達方式

a = [i*2 for i in range(30) if i % 3 is 0]
# Output: [0, 6, 12, 18, 24, 30, 36, 42, 48, 54]

a = [(x,y) for x in [1,2,3] for y in [3,1,4] if x != y]
# Output: [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

  一行程式碼包括了多層迴圈和各種條件,簡潔方便。

  推導式相當於按順序把上下文邏輯放在一行,以列表推導式為例,先把最後要新增進列表的變數放在開頭,然後依次把迴圈和條件判斷排成一行。

  

  

  字典同理

a = {'aa':'aaa'} 
b = {'bb':'bbb'}
c = {'cc':'ccc'}  
d = {'dd':'ddd'}
lista = [a,b,c,d]

attrs = {k:v for x in lista for k, v in x.items()}

attrs = {}
for x in lista:
    for k, v in x.items():
        attrs.update({k:v})
print attrs

  集合有去重效果

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

3. 例項

  更復雜的結構道理相同

a = [1,2,3,4]
b = [5,6,7,8]
c = [1,3,5,7]
d = [2,4,6,8]
lista = [a,b]
listb = [c,d]
listc = [a,c]
listd = [b,d]
liste = [a,d]
listf = [b,c]

listx = [lista,listb,liste]
listy = [listc,listd,listf]
total 
= [listx,listy] att = [w for x in total for y in x for z in y for w in z] print att b = [] for x in total: for y in x: for z in y: for w in z: b.append(w) print b