Get count of tuples in list regardless of elements orders

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

    You can try simple approach without importing anything like this:

    my_list = [(1,12),(12,1),(12,1),(20,15),(7,8),(15,20)]
    
    count={}
    for i in my_list:
        if tuple(sorted(i)) not in count:
            count[tuple(sorted(i))]=1
        else:
            count[tuple(sorted(i))]+=1
    
    print(count)
    

    output:

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

提交回复
热议问题