-4

I want to find occurrence of each set of Cartesian product like

A = [1,2]
B = [2,1]

then

A * B = [(1,2),(1,1),(2,2),(2,1)]

then I want to find occurrence of each set like (1,2) occurs 2 times [(1,2), (2,1)] (1,1) occurs 1 time (1,1) and so on....

randomir
  • 17,989
  • 1
  • 40
  • 55

1 Answers1

0

Try using itertools's product and collections's Counter

from itertools import product
from collections import Counter
A = [1,2]
B = [2,1]
li = list(product(A,B))
li_count =  Counter(tuple(sorted(pair)) for pair in li)

li:

[(1, 2), (1, 1), (2, 2), (2, 1)]

li_count:

Counter({(1, 2): 2, (1, 1): 1, (2, 2): 1})
Pygirl
  • 12,969
  • 5
  • 30
  • 43