2016-08-17 144 views
0

我想添加對象元組內的成本值。我一直在使用一個for循環審判,也使用金額如下嘗試:使用金額以及Python總和for循環花費太長

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

嘗試使用numpy將元組轉換爲數組,然後對它進行求和。如果您的元組名爲t,那麼:

import numpy as np 

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