2016-06-13 29 views
1

我在尋找最有效的方法做如下計算:的Python和2D列表列一致

我有三個矩陣,就像這樣:

[[Brand1, operationCost], [Brand2, operationCost],...] 

[[Brand1, maintenanceCost],[Brand2, maintenanceCost]...] 

[[Brand1, replacementCost],[Brand2, replacementCost]...] 

,我需要計算總成本,運營+維護+更換,每個品牌。可能的是,相同的商標不在所有的矩陣中。並獲得另一個矩陣是這樣的:

[[Brand1, totalCost],[Brand2, totalCost]...]  

回答

2

numpy的應該解決您的問題:

例如:

import numpy as np 
c = np.array([[1, 2, 3], [1, 2, 3]]) 
c.sum(0) 
Out[5]: array([2, 4, 6]) 

如果你想讓你的品牌結合我會用熊貓的變量:

示例:

import pandas as pd 
In[9]: df = pd.DataFrame({'brand1': [1, 2, 3], 'brand2': [1, 2, 3]}) 
In[10]: df 
Out[10]: 
    brand1 brand2 
0  1  1 
1  2  2 
2  3  3 

In[11]: df.sum() 
Out[11]: 
brand1 6 
brand2 6 
+0

一個我有一個問題是,我不能導入numpy的或大熊貓庫在我的項目。 – Madmartigan

1

你似乎不使用Python字典,這應該工作:

operation = [[Brand1, operationCost], [Brand2, operationCost],...] 
maintenance = [[Brand1, maintenanceCost], [Brand2, maintenanceCost],...] 
replacement = [[Brand1, replacementCost], [Brand2, replacementCost],...] 

total = [ [ope[0], ope[1]+mai[1]+rep[1]] for ope,mai,rep in zip(operation,maintenance,replacement) ] 

編輯:

但是你不能用上面這段代碼,如果列出的lenght或順序品牌改變。所以最好的解決方案是使用字典:

# Your matrix as dictionaries 
operation = {Brand1: operationCost, Brand2: operationCost, ...} 
maintenance = {Brand1: maintenanceCost, Brand2: maintenanceCost, ...} 
replacement = {Brand1: replacementCost, Brand2: replacementCost, ...} 
# Get all brands in a container 
all_brands = set(operation.keys()+maintenance.keys()+replacement.keys()) 
# Return 0 as default value if a brand is not in the dictionary 
f = lambda x, dic: dic[x] if x in dic else 0 
# Compute the total cost of each brand 
total = {brand: f(brand,operation)+f(brand,maintenance)+f(brand,replacement) for brand in all_brands} 

或爲2.7版本之前的Python:

total = dict([(brand, f(brand,operation)+f(brand,maintenance)+f(brand,replacement)) for brand in all_brands]) 
+0

即使所有列表的長度不一樣,它也會工作嗎? – Madmartigan

+0

如果矩陣的長度和/或品牌的順序發生變化,它將不起作用。這就是爲什麼我建議你使用字典而不是那些列表。我在編輯我的答案以向你展示。 – cromod

+0

非常感謝@cromod – Madmartigan

1

該解決方案是純Python(它不依賴於第三方的依賴),並應甚至工作如果列表的長度是不一樣的:

oc = [['Brand1', <operationCost>], 
     ['Brand2', <operationCost>], 
     ..., 
     ] 
mc = [['Brand1', <maintenanceCost>], 
     ['Brand2', <maintenanceCost>], 
     ..., 
     ] 
rc = [['Brand1', <replacementCost>], 
     ['Brand2', <replacementCost>], 
     ..., 
     ] 
total = {} 
for lst in [oc, mc, rc]: 
    for brand, cost in lst: 
     total[brand] = total.get(brand, 0) + cost 
+0

非常感謝@Tonechas – Madmartigan