我正在嘗試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')]這里有什么問題?
1 回答

慕勒3428872
TA貢獻1848條經驗 獲得超6個贊
您可以使用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']}
添加回答
舉報
0/150
提交
取消