[英]Create a dict from combinations in a list
我正在尝试从列表中所有可能的元素对创建一个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')]
这里有什么问题?
您可以使用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']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.