Python总和和循环耗时太长

时间:2016-08-17 21:05:04

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

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

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

尝试使用总和:

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。

然而,对于非常大的元组,这两个都需要太长时间。是否有更快的方法来累计成本值?

1 个答案:

答案 0 :(得分:1)

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

import numpy as np

the_sum = np.sum(np.array(t)[:, 1].astype(int))
相关问题