我正在寻找最有效的方法来进行以下计算:
我有三个矩阵,像这样:
[[Brand1, operationCost], [Brand2, operationCost],...]
[[Brand1, maintenanceCost],[Brand2, maintenanceCost]...]
[[Brand1, replacementCost],[Brand2, replacementCost]...]
我需要计算每个品牌的总成本,运营+维护+更换。可以确定的是,相同的标记不在所有矩阵中。并获得另一个这样的矩阵:
[[Brand1, totalCost],[Brand2, totalCost]...]
答案 0 :(得分:2)
Numpy应该解决你的问题:
示例:
import numpy as np
c = np.array([[1, 2, 3], [1, 2, 3]])
c.sum(0)
Out[5]: array([2, 4, 6])
如果你想让你的品牌与变量结合起来我会使用pandas:
示例:
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
答案 1 :(得分:1)
由于您似乎不使用python词典,因此应该可以使用:
[Object]0:
Object
barcode: "abc"
name: "barcoded"
sellPrice: "122"
unit: "200"
__proto__:Object
length: 1
__proto__: Array[0]
修改:
但是,如果列表的长度或品牌的顺序发生变化,则您无法使用上述代码。所以最好的解决方案是使用词典:
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) ]
或者对于2.7版本之前的python:
# 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 :(得分: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