0

我想要我正在编写的脚本的一部分来做这样的事情。

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 因为它没有搜索单个列表。我怎样才能让它返回实例总数?

4

3 回答 3

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
于 2013-07-18T17:04:24.083 回答
1

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

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

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

应该这样做

于 2013-07-18T17:04:46.980 回答
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

我过滤掉了ints,因为我不明白你为什么首先拥有它们。

于 2013-07-18T17:18:56.740 回答