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

时间:2013-07-18 17:03:08

标签: python list

我希望我写的一部分脚本可以做这样的事情。

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)

问题是这将打印0,因为它没有搜索单个列表。如何让它返回实例总数?

3 个答案:

答案 0 :(得分:6)

搜索每个子列表,将每个包含列表的结果与sum()相加:

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

演示:

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

答案 1 :(得分:1)

sum()是一个用于添加其参数的内置函数。

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

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

应该这样做

答案 2 :(得分:0)

使用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

我过滤掉了int,因为我不知道你为什么要把它们放在首位。