简体   繁体   中英

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?

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

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

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 int s because I didn't see why you had them in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM