Skip to main content
 首页 » 编程设计

python之如何以 python 方式计算对象列表中所有计数的总数

2025年05月04日26lori

我有一个包含 .count() 方法的对象列表。我现在想要所有对象的总数。以下作品:

count = 0 
for the_obj in obj_list: 
    count += the_obj.count() 
print count 

但我感觉有更多 Pythonic 方式可以做到这一点。有人有提示吗?

请您参考如下方法:

您可以使用内置的 sum()使用生成器对各个计数求和。

count = sum(obj.count() for obj in obj_list) 

或者(虽然不是必需的),一种功能性的方法是使用 reduce和 map , 与 methodcaller调用方法。

from operator import add, methodcaller 
count = reduce(add, map(methodcaller('count'), obj_list))