我想在一个循环中一次对多个属性求和:
class Some(object):
def __init__(self, acounter, bcounter):
self.acounter = acounter
self.bcounter = bcounter
someList = [Some(x, x) for x in range(10)]
我可以做一些比它更简单、更快的事情吗?
atotal = sum([x.acounter for x in someList])
btotal = sum([x.bcounter for x in someList])
请您参考如下方法:
首先 - sum 不需要列表 - 你可以使用生成器表达式来代替:
atotal = sum(x.acounter for x in someList)
您可以编写一个辅助函数来搜索列表一次,然后按项目依次查找每个属性,例如:
def multisum(iterable, *attributes, **kwargs):
sums = dict.fromkeys(attributes, kwargs.get('start', 0))
for it in iterable:
for attr in attributes:
sums[attr] += getattr(it, attr)
return sums
counts = multisum(someList, 'acounter', 'bcounter')
# {'bcounter': 45, 'acounter': 45}
