如何用一个循环过程对多个对象属性求和(求和)?

2024-06-26 03:11:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

class Some(object):
    def __init__(self, acounter, bcounter):
        self.acounter = acounter
        self.bcounter = bcounter

someList = [Some(x, x) for x in range(10)]

我能做些比这更简单、更快的事吗?在

^{pr2}$

Tags: inselffor属性objectinitdefrange
3条回答

首先-sum不需要列表-可以使用生成器表达式代替:

atotal = sum(x.acounter for x in someList)

您可以编写一个helper函数来对列表进行一次搜索,但要按项目依次查找每个属性,例如:

^{pr2}$

另一种方法(可能不会更快)是为类重载加法运算符:

class Some(object):
  def __init__(self, acounter, bcounter):
    self.acounter = acounter
    self.bcounter = bcounter

  def __add__(self, other):
    if isinstance(other, self.__class__):
      return Some(self.acounter+other.acounter, self.bcounter+other.bcounter)
    elif isinstance(other, int):
      return self
    else:
      raise TypeError("useful message")

  __radd__ = __add__

somelist = [Some(x, x) for x in range(10)]

combined = sum(somelist)
print combined.acounter
print combined.bcounter

这样,sum返回一个Some对象。在

我怀疑这是不是真的更快,但你可以这样做:

首先通过以下方式定义padd(用于“pair add”):

def padd(p1,p2): 
    return (p1[0]+p2[0],p1[1]+p2[1])

例如,padd((1,4), (5,10)) = (6,14)

然后使用reduce

^{pr2}$

在python3中,您需要从functools导入reduce,但是IIRC它可以直接在python2中使用。在

编辑时:对于2个以上的属性,可以将padd替换为vadd(“vector add”),它可以处理任意维度的元组:

^{3}$

对于两个属性,硬连接维度可能更有效,因为函数调用开销更小。在

相关问题 更多 >