Counting the amount of occurrences in a list of tuples

后端 未结 3 1885
余生分开走
余生分开走 2021-02-04 01:44

I am fairly new to python, but I haven\'t been able to find a solution to my problem anywhere.

I want to count the occurrences of a string inside a list of tuples.

3条回答
  •  既然无缘
    2021-02-04 01:53

    list1.count(entry[0]) will not work because it looks at each of the three tuples in list1, eg. ('12392', 'some string', 'some other string') and checks if they are equal to '12392' for example, which is obviously not the case.

    @eurmiro's answer shows you how to do it with Counter (which is the best way!) but here is a poor man's version to illustrate how Counter works using a dictionary and the dict.get(k, [,d]) method which will attempt to get a key (k), but if it doesn't exist it returns the default value instead (d):

    >>> list1 = [
             ('12392', 'some string', 'some other string'),
             ('12392', 'some new string', 'some other string'),
             ('7862', None, 'some other string')
    ]
    >>> d = {}
    >>> for x, y, z in list1:
            d[x] = d.get(x, 0) + 1
    
    
    >>> d
    {'12392': 2, '7862': 1}
    

提交回复
热议问题