Get count of tuples in list regardless of elements orders

前端 未结 4 1734
你的背包
你的背包 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:15

    You can swap all positions by size and then use collections.counter:

    from collections import Counter
    l = [(1,12),(12,1),(12,1),(20,15),(7,8),(15,20)]
    new_l = Counter([[(b, a), (a, b)][a < b] for a, b in l])
    for a, b in new_l.items():
      print('{},{}:{}'.format(*(list(a)+[b])))
    

    Output:

    15,20:2
    7,8:1
    1,12:3
    

提交回复
热议问题