Reputation: 33
I have a list of lists in the form:
[[(1, 2), (2, 1)], [(1, 2), (1, 2)], [(2, 3), (2, 2)]]
I would like to know the number of times a given tuple occurs in the zeroeth position of each sublist. In the above example, if I wanted to find the count of (1, 2), I would expect to return 2, for the number of times (1, 2) appears as the first item in a sublist.
I've tried using list.count(), but that seems to be limited to occurrences in the first list and not able to parse positions within the sublists.
I've also looked into Counter(), but that also doesn't seem to give what I want.
Upvotes: 3
Views: 209
Reputation: 7922
This may not be very elegant, but I'm just playing around...
>>> lst
[[(1, 2), (2, 1)], [(1, 2), (1, 2)], [(2, 3), (2, 2)]]
>>> (lambda x: [l[0] == (1,2) for l in x].count(True) )(lst)
2
>>> (lambda list,tuple: [l[0] for l in list].count(tuple) )(lst, (1,2))
2
>>> z=0
>>> for ll in lst:
... if ll[0] == (1,2): z+=1
...
>>> z
2
Upvotes: 0
Reputation: 26397
>>> from collections import Counter
>>> lst = [[(1, 2), (2, 1)], [(1, 2), (1, 2)], [(2, 3), (2, 2)]]
>>> c = Counter(sublst[0] for sublst in lst)
>>> c
Counter({(1, 2): 2, (2, 3): 1})
>>> c[(1, 2)]
2
Upvotes: 4
Reputation: 13259
a = [[(1, 2), (2, 1)], [(1, 2), (1, 2)], [(2, 3), (2, 2)]]
item = (1,2)
count = [sublist[0] for sublist in a].count(item)
Upvotes: 2