gpt4 book ai didi

python - 如何通过一次循环对多个对象属性求和(求和)?

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:46 26 4
gpt4 key购买 nike

我想在一个循环中一次对多个属性求和:

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}

关于python - 如何通过一次循环对多个对象属性求和(求和)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32035495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com