Count the duplicates in a list of tuples

后端 未结 5 1582
时光取名叫无心
时光取名叫无心 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:13

    use collections library. In the following code val_1, val_2 give you duplicates of each first elements and second elements of the tuples respectively.

    import collections
    val_1=collections.Counter([x for (x,y) in a])
    val_2=collections.Counter([y for (x,y) in a])
    
    >>> print val_1
    <<< Counter({1: 3, 2: 1, 6: 1})
    

    This is the number of occurrences of the first element of each tuple

    >>> print val_2
    <<< Counter({2: 2, 9: 1, 4: 1, 7: 1})
    

    This is the number of occurrences of the second element of each tuple

提交回复
热议问题