【问题标题】:Python sum and for loop taking too longPython sum 和 for 循环耗时太长
【发布时间】:2016-08-17 21:05:04
【问题描述】:

我正在尝试在对象元组中添加成本值。我尝试过使用 for 循环,也尝试过使用 sum,如下所示:

def cost_from_start(self, path):
    cost = -1
    for node in path:
        cost+=node.cost
    return cost

也尝试使用 sum:

def cost_from_start(self, path):
    return sum(arc.cost for arc in path)

对象元组如下所示:

(Arc(label='no action', cost=0), Arc(label='SW', cost=1), Arc(label='SW', cost=1), Arc(label='W', cost=1))

除第一个对象外,每个对象的所有成本值为 1。

但是,对于非常大的元组来说,这两种方法都需要很长时间。有没有更快的方法来计算成本值?

【问题讨论】:

    标签: python-3.x object for-loop sum tuples


    【解决方案1】:

    尝试使用 numpy 将元组转换为数组并对其使用 sum。如果你的元组被称为t,那么:

    import numpy as np
    
    the_sum = np.sum(np.array(t)[:, 1].astype(int))
    

    【讨论】:

      猜你喜欢
      • 2017-11-06
      • 1970-01-01
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 2016-12-07
      • 2018-01-05
      相关资源
      最近更新 更多