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.
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}