How to get the frequency of the tuples in a list of tuples when the order inside each tuple doesn’t matte with Python

2 Answers

0 votes
from collections import Counter

tpl_lst = [(1, 2, 3), (3, 1, 2), (2, 3, 1), (4, 5, 6), (8, 7, 1), (6, 4, 5)]

normalized = [tuple(sorted(t)) for t in tpl_lst]

freq = Counter(normalized)

print(freq)



'''
run:

Counter({(1, 2, 3): 3, (4, 5, 6): 2, (1, 7, 8): 1})

'''

 



answered Jan 14 by avibootz
0 votes
def unordered_tuple_frequencies(tpl_lst):
    freq = {}
    for t in tpl_lst:
        key = tuple(sorted(t))   # normalize tuple so order doesn't matter
        freq[key] = freq.get(key, 0) + 1
    return freq

tpl_lst = [
    (1, 2, 3), (3, 1, 2), (2, 3, 1),
    (4, 5, 6), (8, 7, 1), (6, 4, 5)
]

freq = unordered_tuple_frequencies(tpl_lst)

print(freq)




'''
run:

{(1, 2, 3): 3, (4, 5, 6): 2, (1, 7, 8): 1}

'''

 



answered Jan 14 by avibootz
...