Get count of tuples in list regardless of elements orders

前端 未结 4 1738
你的背包
你的背包 2021-01-24 08:31

I have a list of tuples that looks something like this:

my_list = [(1,12),(12,1),(12,1),(20,15),(7,8),(15,20)]

I want to get a count of the num

4条回答
  •  无人共我
    2021-01-24 09:01

    You can use collections.Counter, normalizing your elements with sorted first.

    from collections import Counter
    
    lst = [(1,12),(12,1),(12,1),(20,15),(7,8),(15,20)]
    
    count = Counter(tuple(sorted(t)) for t in lst)
    # output: Counter({(1, 12): 3, (15, 20): 2, (7, 8): 1})
    

    You can then print like so.

    for value, amount in count.items():
        print(value, '=', amount)
    
    # Prints: 
    # (1, 12) = 3
    # (15, 20) = 2
    # (7, 8) = 1
    

提交回复
热议问题