简体   繁体   English

如何在列表列表中查找项目的实例数

[英]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? 问题在于这将打印0,因为它没有搜索单个列表。如何使它返回实​​例总数?

Search per sublist , adding up results per contained list with sum() : 搜索每个子列表 ,使用sum()将每个包含的列表的结果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. sum()是用于添加其参数的内置函数。

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. x.count(item) for x in list)x.count(item) for x in list)是一个“生成器表达式”(类似于列表推导)-一种在python中创建和管理列表对象的便捷方法。

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

That should do it 那应该做

Using collections.Counter and itertools.chain.from_iterable : 使用collections.Counteritertools.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. 我过滤掉了int因为我不明白为什么你首先拥有它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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