我想要我正在编写的脚本的一部分来做这样的事情。
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 因为它没有搜索单个列表。我怎样才能让它返回实例总数?
搜索每个子列表,将每个包含列表的结果相加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
sum()
是一个用于将其参数相加的内置函数。
这x.count(item) for x in list)
是一个“生成器表达式”(类似于列表推导式)——一种在 python 中创建和管理列表对象的便捷方式。
item_count = sum(x.count(item) for x in list)
应该这样做
使用collections.Counter
和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
我过滤掉了int
s,因为我不明白你为什么首先拥有它们。