3 回答

TA貢獻1779條經驗 獲得超6個贊
Python 附帶電池,但最干凈的方法并不總是顯而易見的。您已經擁有想要內置的功能itertools。
試試這個:
import itertools
result = {f'{k1}#{k2}': d[k1]*d[k2]
for k1, k2 in itertools.combinations_with_replacement(d, 2)}
itertools.combinations為您提供所有沒有重復的對,itertools.combinations_with_replacement為您提供唯一的對,包括密鑰相同的對。
輸出:
>>> print(result)
{'a#a': 0, 'a#b': 0, 'a#c': 0, 'b#b': 1, 'b#c': 2, 'c#c': 4}

TA貢獻1784條經驗 獲得超2個贊
您可以為此使用 dict 理解:
dd = {f'{k}#{l}': v*w for k,v in d.items() for l,w in d.items() if k<=l}
>>> {'a#a': 0, 'a#b': 0, 'a#c': 0, 'b#b': 1, 'b#c': 2, 'c#c': 4}
編輯:如果您希望結果按 d 中的項目幻影排序:
d = {'b': 0, 'a': 1, 'c': 2}
dd = {f'{k}#{l}': v*w
for i,(k,v) in enumerate(d.items())
for j,(l,w) in enumerate(d.items())
if i<=j}
>>> {'b#b': 0, 'b#a': 0, 'b#c': 0, 'a#a': 1, 'a#c': 2, 'c#c': 4}

TA貢獻1860條經驗 獲得超8個贊
您可以使用 itertools 獲取組合并形成字典!
>>> from itertools import combinations
>>>
>>> d
{'a': 0, 'c': 2, 'b': 1}
>>> combinations(d.keys(),2) # this returns an iterator
<itertools.combinations object at 0x1065dc100>
>>> list(combinations(d.keys(),2)) # on converting them to a list
[('a', 'c'), ('a', 'b'), ('c', 'b')]
>>> {"{}#{}".format(v1,v2): (v1,v2) for v1,v2 in combinations(d.keys(),2)} # form a dict using dict comprehension, with "a#a" as key and a tuple of two values.
{'a#c': ('a', 'c'), 'a#b': ('a', 'b'), 'c#b': ('c', 'b')}
>>> {"{}#{}".format(v1,v2): d[v1]*d[v2] for v1,v2 in combinations(d.keys(),2)}
{'a#c': 0, 'a#b': 0, 'c#b': 2} # form the actual dict with product as values
>>> {"{}#{}".format(v1,v2):d[v1]*d[v2] for v1,v2 in list(combinations(d.keys(),2)) + [(v1,v1) for v1 in d.keys()]} # form the dict including the self products!
{'a#c': 0, 'a#b': 0, 'a#a': 0, 'b#b': 1, 'c#c': 4, 'c#b': 2}
或者像鄧肯指出的那樣簡單,
>>> from itertools import combinations_with_replacement
>>> {"{}#{}".format(v1,v2): d[v1]*d[v2] for v1,v2 in combinations_with_replacement(d.keys(),2)}
{'a#c': 0, 'a#b': 0, 'a#a': 0, 'b#b': 1, 'c#c': 4, 'c#b': 2}
添加回答
舉報