【问题标题】:python get second value of a tuple in a list [duplicate]python获取列表中元组的第二个值[重复]
【发布时间】:2016-02-18 22:18:25
【问题描述】:

我有以下列表:parent_child_list 带有 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]

但不幸的是,我忘记了 dict 不能有 double 值,所以我没有得到 965、988 作为答案,而是只收到 965。

有什么简单的方法可以保留双精度值吗?

非常感谢

【问题讨论】:

    标签: python list dictionary key tuples


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您已经获得了使用列表推导或循环提取个体的方法,但您可以为所有值构建所需的字典:

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

      除了使用原始 python dict,您可以使用 collections.defaultdict(list) 并直接使用 append,例如d[parent].append(child)

      【讨论】:

        【解决方案3】:

        列表理解

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

        将为您提供 x 值等于 960 的元组的 y 值列表。

        【讨论】:

          【解决方案4】:

          你总是可以迭代:

          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)
          

          【讨论】:

            【解决方案5】:

            您可以使用列表解析来构建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]
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2014-04-20
              • 1970-01-01
              • 2016-07-27
              • 2019-11-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-12-31
              相关资源
              最近更新 更多