【问题标题】:How do I get all possible combinations of a list to put into a dictionary, such as (a,b) and (b,a)?如何将列表的所有可能组合放入字典中,例如 (a,b) 和 (b,a)?
【发布时间】:2021-05-09 23:12:36
【问题描述】:

我的代码有问题:

 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)}

提前致谢

【问题讨论】:

  • 你需要itertools.permutations而不是combinations
  • 正如@AnkurSaxena 所说,在这种情况下需要排列,因为我们确实关心值的顺序,因为组合 321 和 123 是相同的,并且只使用了一个

标签: python dictionary collections itertools


【解决方案1】:

正如我在 cmets 中提到的,您需要 permutations 而不是来自 itertoolscombinations。下面的代码有效。如果您的目标是简单地获取一个计数字典,您可以简单地执行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}

【讨论】:

  • AWW 谢谢大家!我将再看一下 itertools。
【解决方案2】:

使用排列而不是组合

从 itertools 导入排列 count = Counter(permutations(n, 2))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多