Python sum 2D list列

2024-10-16 22:24:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找最有效的方法来进行以下计算:

我有三个矩阵,像这样:

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

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

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

我需要计算每个品牌的总成本,运营+维护+更换。不可能所有的矩阵中都有相同的标记。得到另一个矩阵如下:

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

Tags: 方法标记矩阵品牌totalcost总成本brand1brand2
3条回答

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

由于您似乎不使用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) ]

编辑:

不过,如果列表长度或品牌顺序发生变化,则不能使用上述代码。所以最好的解决办法是使用字典:

# 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])

此解决方案是纯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

相关问题 更多 >