【问题标题】:Create a dict from combinations in a list从列表中的组合创建字典
【发布时间】:2018-10-03 15:06:42
【问题描述】:

我正在尝试从列表中所有可能的元素对创建dict。这是我尝试过的。

>>from itertools import combinations
>>l = ['a','b','c']
>>dict(combinations(l,2))
{'a': 'c', 'b': 'c'}

这是错误的,因为有 3 种可能的组合。它缺少'a': 'b'。然而,当我list(combinations(l,2)) 时,它给了我所有可能的组合:

[('a', 'b'), ('a', 'c'), ('b', 'c')]

这里有什么问题?

【问题讨论】:

  • 字典不能有重复的键。 {'a': 'b'}{'a': 'c'} 覆盖
  • 您可以使用以下内容:print ([(i, j) for i in l for j in l if i<j]),答案为[('a', 'b'), ('a', 'c'), ('b', 'c')]
  • @Bazingaa 我认为你错过了他们试图提出的观点。元组列表是为了说明配对确实存在,但最终没有出现在最终字典中,这是由于我提到的重复键问题
  • 嗯,我明白了。确实如此。尽管如此,我还是会留下我的评论,因为它为这个特定列表提供了替代组合 l

标签: python python-3.x dictionary combinations


【解决方案1】:

您可以使用defaultdict 来创建到值列表的映射:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for k, *v in combinations(l, 2):
...     d[k].extend(v)
... 
>>> dict(d)
{'a': ['b', 'c'], 'b': ['c']}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 2021-04-03
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 2019-06-02
    • 2011-08-29
    相关资源
    最近更新 更多