David Greydanus
David Greydanus

Reputation: 2567

How to find the number of instances of an item in a list of lists

I want part of a script I am writing to do something like this.

x=0
y=0
list=[["cat","dog","mouse",1],["cat","dog","mouse",2],["cat","dog","mouse",3]]

row=list[y]
item=row[x]
print list.count(item)

The problem is that this will print 0 because it isn't searching the individual lists.How can I make it return the total number of instances instead?

Upvotes: 0

Views: 277

Answers (3)

secretmike
secretmike

Reputation: 9884

sum() is a builtin function for adding up its arguments.

The x.count(item) for x in list) is a "generator expression" (similar to a list comprehension) - a handy way to create and manage list objects in python.

item_count = sum(x.count(item) for x in list)

That should do it

Upvotes: 1

2rs2ts
2rs2ts

Reputation: 11026

Using collections.Counter and itertools.chain.from_iterable:

>>> from collections import Counter
>>> from itertools import chain
>>> lst = [["cat","dog","mouse",1],["cat","dog","mouse",2],["cat","dog","mouse",3]]
>>> count = Counter(item for item in chain.from_iterable(lst) if not isinstance(item, int))
>>> count
Counter({'mouse': 3, 'dog': 3, 'cat': 3})
>>> count['cat']
3

I filtered out the ints because I didn't see why you had them in the first place.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121416

Search per sublist, adding up results per contained list with sum():

sum(sub.count(item) for sub in lst)

Demo:

>>> lst = [["cat","dog","mouse",1],["cat","dog","mouse",2],["cat","dog","mouse",3]]
>>> item = 'cat'
>>> sum(sub.count(item) for sub in lst)
3

Upvotes: 6

Related Questions