【问题标题】:Python list of tuples: organize by unique elements to a dictionaryPython 元组列表:按唯一元素组织到字典中
【发布时间】:2012-05-16 08:29:00
【问题描述】:

我有一个元组列表,比如说:

list_of_tuples = [('a', 1),('b',2),('c',1),('a',2),('d',3)]

我需要获取元组中任何(唯一)第二个元素的对应值。例如作为字典。 输出:

dict = {1:['a','c'],2:['b','a'],3:['d']}

最pythonic的方式是什么?非常感谢!

【问题讨论】:

    标签: python list dictionary tuples


    【解决方案1】:

    我可能会选择像 jamylak 这样的 defaultdict,但如果你想要一个“真正的”字典,你可以使用 setdefault()

    >>> list_of_tuples = [('a', 1),('b',2),('c',1),('a',2),('d',3)]
    >>> d = {}
    >>> for item in list_of_tuples:
    ...     d.setdefault(item[1],[]).append(item[0])
    ...
    >>> d
    {1: ['a', 'c'], 2: ['b', 'a'], 3: ['d']}
    

    【讨论】:

      【解决方案2】:
      >>> from collections import defaultdict
      >>> list_of_tuples = [('a', 1),('b',2),('c',1),('a',2),('d',3)]
      >>> d = defaultdict(list)
      >>> for c,num in list_of_tuples:
              d[num].append(c)
      
      
      >>> d
      defaultdict(<type 'list'>, {1: ['a', 'c'], 2: ['b', 'a'], 3: ['d']})
      

      【讨论】:

      • defaultdict 主要在默认构造昂贵时有用;空列表不是这种情况 - 最好只使用普通字典并执行d.setdefault(num, []).append(c)
      • @Ivc:可能是这样,但除非性能确实是这里的相关问题,否则我发现 defaultdicts 更容易理解。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-16
      • 1970-01-01
      • 2018-01-17
      • 2014-03-31
      • 2013-02-23
      相关资源
      最近更新 更多