Count the duplicates in a list of tuples

后端 未结 5 1524
时光取名叫无心
时光取名叫无心 2021-01-18 15:45

I have a list of tuples: a = [(1,2),(1,4),(1,2),(6,7),(2,9)] I want to check if one of the individual elements of each tuple matches the same position/element i

5条回答
  •  北恋
    北恋 (楼主)
    2021-01-18 16:22

    Maybe Dictionary can work better. Because in your code, you are traveling the list for twice. And this makes the complexity of your code O(n^2). And this is not a good thing :)

    Best way is the travelling for once and to use 1 or 2 conditions for each traverse. Here is the my first solution for such kind of problem.

    a = [(1,2),(1,4),(1,2),(6,7),(2,9)]
    
    dict = {}
    for (i,j) in a:
        if dict.has_key(i):
                dict[i] += 1
        else:
                dict[i] = 1
    
    print dict
    

    For this code, this will give the output:

    {1: 3, 2: 1, 6: 1}
    

    I hope it will be helpful.

提交回复
热议问题