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!
This should do it:
counter = Counter(tuple(sorted(tup)) for tup in your_list)
print counter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With