Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting tuples in a list, no matter the order of each element within the tuples

I have a question about counting occurrences within a list in Python.

Here's the list:

aList = [(11, 0), (9, 7), (23, 9), (25, 3), (9, 9), (21, 2), (10, 9), (14, 14), (8, 13), (14, 9), (11, 4), (1, 14), (3, 9), (3, 1), (11, 9), (9, 1), (7, 0), (9, 3), (9, 3), (16, 11), (9, 7), (9, 13), (11, 9), (26, 18), (18, 9), (11, 14), (9, 9), (24, 26), (12, 21), (1, 14), (3, 14), (15, 14), (26, 9), (11, 3), (4, 14), (9, 14), (26, 4), (7, 26), (9, 3), (13, 3), (9, 24), (14, 9), (3, 26), (7, 25), (5, 9), (9, 5), (14, 4), (9, 0), (4, 26), (4, 26), (9, 9), (18, 18), (9, 7), (7, 6), (9, 9), (14, 13), (11, 9), (3, 9), (9, 15), (25, 9), (10, 24), (0, 4), (10, 3), (8, 12), (9, 4), (20, 9), (9, 9), (6, 9), (9, 8), (9, 9), (24, 16), (9, 11), (14, 9), (7, 12), (1, 9), (9, 13), (5, 13), (9, 9), (25, 9), (4, 9), (1, 3), (10, 9), (12, 9), (9, 9), (11, 11), (14, 3), (9, 25), (16, 1), (25, 16), (25, 16), (5, 9), (9, 3), (5, 1), (10, 24), (10, 25), (24, 1), (9, 1), (24, 9), (9, 7), (25, 3)]

As you can see, this is a list of tuples. I need to count the occurrences of each tuple no matter the order of each element within the tuples.

I'm trying to use Collections' counter like this:

cnt = Counter()
for l in aList:
    cnt[l] += 1

print cnt

Tuples like (3, 9) and (9, 3) should be counted as identical, which my code doesn't do right now. Is there a way to achieve this kind of counts with counter? Or should I use another method?

Thanks!

like image 263
Lucien S. Avatar asked Feb 09 '23 08:02

Lucien S.


1 Answers

This should do it:

counter = Counter(tuple(sorted(tup)) for tup in your_list)
print counter
like image 125
Cyphase Avatar answered Feb 12 '23 01:02

Cyphase