1
我有一个有.count()
方法的对象列表。我现在想要所有对象的总数。以下作品:如何pythonically使对象列表中的所有计数的总数?
count = 0
for the_obj in obj_list:
count += the_obj.count()
print count
但我有这样的感觉,有更多的Pythonic这样做。任何人有小费?
我有一个有.count()
方法的对象列表。我现在想要所有对象的总数。以下作品:如何pythonically使对象列表中的所有计数的总数?
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))
简洁而明确的答案,用更好的选择完全解释做'总之,爱这个答案 – Netwave
你可以(在OBJ_LIST OBJ obj.count())' – thefourtheye