首页 > 解决方案 > 元素/值的计数出现在列表列表中

问题描述

如何计算元素/值在列表列表中出现的次数?

我想返回测试发生的次数。

my_list = [['test', 'idk', 'blah'], ['test', 'idk', 'blah'], ['test', 'idk', 'blah'], ['test', 'idk', 'blah'], ['test', 'idk', 'blah']]
print(my_list.count('test'))
>>> 0

所需输出:5

其次,我只想检查/计数测试每个列表的第一个元素,例如my_list[0/1/2/...][0]

标签: pythonpython-3.xlistcountslice

解决方案


试试这个:

print(sum(x.count('test') for x in my_list))
# 5

推荐阅读