Get count of tuples in list regardless of elements orders

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

    First you can sort your list

    lst2 = [tuple(sorted(i)) for i in lst]
    

    Then you can use set() to find the unique values in this list and count their occurence.

    count = {}
    for i in set(lst2):
        num = len([1 for j in lst2 if j == i])
        count.update({i:num})
    print(count)
    

    {(1, 12): 3, (7, 8): 1, (15, 20): 2}

提交回复
热议问题