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}
添加回答
举报