繁体   English   中英

查找列表中子列表元素的累积计数的有效方法

[英]efficient way to find cumulative count for the elements of a sublist in a list

要查找另一个列表中元素列表的累积计数,我可以遍历子列表中每个元素的列表(通过 list.count)并将它们相加。 是否可以使用更有效的 Pythonic 方式实现相同的效果?

例子:

test_list = [1,1,2,2,2,3,3,3,4,5,5,5]
to_be_counted = [1,2]
result = 5 (1 two times, 2 three times)

尝试mapsum

test_list = [1,1,2,2,2,3,3,3,4,5,5,5]
to_be_counted = [1, 2]
print(sum(map(test_list.count, to_be_counted)))

暂无
暂无

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

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