2016-06-13 65 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