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

python get second value of a tuple in a list

我有以下列表:parent_child_list with id-tuples:

[(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。

是否有任何简单的选项来保留双精度值?

非常感谢

您可以使用列表推导式构建 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)

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