如何将列表的所有可能组合放入字典中,例如 (a,b) 和 (b,a)?

How do I get all possible combinations of a list to put into a dictionary, such as (a,b) and (b,a)?

我的代码有问题:

 from collections import Counter
 from collections import defaultdict
 from itertools import combinations

 def findPairs(pair_counts, n): 

      
      pair_counts = dict() 
      count = Counter(combinations(n, 2))

      for key, value in count.items():
          pair_counts[key] = value
      print(pair_counts)


 nums = [2,3,7]
 #n = len(nums)
 findPairs(pair_counts, nums)

它给出了输出:

{(2, 3): 1, (2, 7): 1, (3, 7): 1}

但我希望它的输出看起来更像:

{(2, 3): 1, (2, 7): 1, (3, 7): 1, (3,2):1, (7,2):1, (7,3):1)}

提前致谢

正如我在评论中提到的,您需要 permutations 而不是 itertools 中的 combinations。下面的代码有效。如果你的目标是简单地得到一个计数字典,你可以简单地 dict(Counter(...)) 将它转换成字典。
此外,删除了一些不必要的代码行。

from collections import Counter
from itertools import permutations

def findPairs(n): 
    ###
    pair_counts = dict() 
    count = dict(Counter(permutations(n, 2)))
    print(count)


nums = [2,3,7]
findPairs(nums)

# Output
# {(2, 3): 1, (2, 7): 1, (3, 2): 1, (3, 7): 1, (7, 2): 1, (7, 3): 1}

使用排列代替组合

从 itertools 导入排列 计数 = 计数器(排列(n,2))