簡體   English   中英

從列表中的組合創建字典

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM