Python获取列表中元组的第二个值

3
我有以下列表: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作为答案,而不是965和988。
有没有简单的选项可以保留双精度值?
非常感谢。
5个回答

5
您可以使用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)

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 的元组的 y 值。


0
您已经学习了使用列表推导式或循环提取个别元素的方法,但是您也可以构建所需的包含所有值的字典:
>>> 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)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接