Search code examples
pythonpython-3.xlisttuplespython-itertools

Compare all elements of list between themselves


How do I count the occurrences of tuples in a list, regardless of the order of the tuple's items? For example;

the_list = [
    (one, two, three),
    (two, three, four),
    (one, three, two),
    (one, two, three),
    (four, two, one),
]

In the list above I want (one, two, three) and (one, three, two) to be equal and be counted as the same thing.


Solution

  • You can use a counter and sort them before you start counting

    thelist = [(1,2,3), (2,3,4), (1,3,2), (1,2,3), (4,2,1)]
    from collections import Counter
    Counter(tuple(sorted(x)) for x in thelist)
    
    Counter({(1, 2, 3): 3, (2, 3, 4): 1, (1, 2, 4): 1})