一只斗牛犬
您可以为此使用 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}
桃花长相依
您可以使用 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}