Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

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

I have an issue with my code:

 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)

It gives an output of:

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

BUT I want it to give an output that looks more like:

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

Thanks in advance

question from:https://stackoverflow.com/questions/66066186/how-do-i-get-all-possible-combinations-of-a-list-to-put-into-a-dictionary-such

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As I mentioned in comments, you need permutations instead of combinations from itertools. Below code works. And if your aim is to simply get a dictionary of count, you can simply do dict(Counter(...)) to convert it into dict.
Also, removed some unnecessary code lines.

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}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...