2015-11-17 63 views
1

我已經以下列表:parent_child_list ID爲元組:蟒得到的元組的第二值在列表

[(960, 965), (960, 988), (359, 364), (359, 365), 
(361, 366), (361, 367), (361, 368), (361, 369), 
(360, 370), (360, 371), (360, 372), (360, 373), (361, 374)] 

實施例:我想打印的組合與ID 960那些將這些值爲:965,988

我試圖列表轉換成一個字典:

rs = dict(parent_child_list) 

因爲現在我可以簡單地說:

print rs[960] 

可惜我忘了,字典不能有雙重價值,從而不但得不到965,988,我只收到965

有沒有簡單的選項,以防止雙重價值的答案?

非常感謝

回答

3

您可以使用defaultdict創建帶有列表的字典作爲其值類型,然後附加值。

from collections import defaultdict 
l = [(960, 965), (960, 988), (359, 364), (359, 365), (361, 366), (361, 367), (361, 368), (361, 369), (360, 370), (360, 371), (360, 372), (360, 373), (361, 374)] 

d = defaultdict(list) 

for key, value in l: 
    d[key].append(value) 
+0

完美。謝謝 – Constantine

1

您可以使用列表理解構建list,使用if篩選出匹配ID:

>>> parent_child_list = [(960, 965), (960, 988), (359, 364), (359, 365)] 
>>> [child for parent, child in parent_child_list if parent == 960] 
[965, 988] 
0

你總是可以迭代:

parent_child_list = [(960, 965), (960, 988), (359, 364), (359, 365), 
(361, 366), (361, 367), (361, 368), (361, 369), 
(360, 370), (360, 371), (360, 372), (360, 373), (361, 374)] 

for key, val in parent_child_list: 
    if key == 960: 
     print str(val) 
0

名單理解

[y for (x, y) in parent_child_list if x == 960] 

會給你一個元組,其X值等於960

0

你已經拿到使用列表理解或循環提取個人的方式,但你可以構造你的所有慾望值的字典y值的列表:

>>> d = {} 
>>> for parent, child in parent_child_list: 
...  d.setdefault(parent, []).append(child) 
>>> d[960] 
[965, 988] 

替代使用原始的Python字典,你可以使用一個collections.defaultdict(list)而直接append,如d[parent].append(child)

相關問題