蟒得到的元组的第二值在列表
问题描述:
我已经以下列表: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
有没有简单的选项,以防止双重价值的答案?
非常感谢
答
您可以使用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)
答
您可以使用列表理解构建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]
答
你总是可以迭代:
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)
答
名单理解
[y for (x, y) in parent_child_list if x == 960]
会给你一个元组,其X值等于960
答
你已经拿到使用列表理解或循环提取个人的方式,但你可以构造你的所有欲望值的字典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)
完美。谢谢 – Constantine