如何基于索引添加子列表的元素 - Python

问题描述 投票:2回答:2

如何根据值的索引在子列表中添加元素?例如,你怎么转这个:

nested_list = [[1,2],[3,4],[5,6]]

进入这个? :

sublist_sums = [9,12] # [1 + 3 + 5, 2 + 4 + 6]

对不起,如果标题不是很清楚,我真的不确定如何把它。

python python-3.x list sum nested-lists
2个回答
2
投票

如果允许使用NumPy,那么你可以在numpy.sum()上使用axis=0

In [11]: np.sum(nested_list, axis=0)
Out[11]: array([ 9, 12])

另一方面,如果你想要一个简单的Python解决方案,那么在列表理解中使用ziped结果就足够了:

In [32]: [sum(l) for l in zip(*nested_list)]
Out[32]: [9, 12]

1
投票

已经接受了答案,但以下内容也可以用于您的要求。让我知道这是否回答了您的问题。

import pandas as pd
import numpy as np

c = ['Val1','Val2'] 
v = [
        [1,1.0],
        [2,1.0],
        [1,1.0],
        [2,0.98],
        [3,0.78],
        [4,0.70],
        [9,0.97],
        [6,0.67],
        [12,0.75],

    ]



n = len(v)

df = pd.DataFrame(v,columns=c)


#Take top N ie all elements in this case and sum it.
print(list(df.groupby('Val1').head(n).sum()))  

#### Output ####
[40.0, 7.85]




#Alternatively you can create a column where the value is same for all
#In my case column is 'id' and value is 1
#Then apply group-by-sum on 'id'
df['id'] = [1]*n   
print(df.groupby('id').sum())

#### Output ####
    Val1  Val2
id            
1     40  7.85
© www.soinside.com 2019 - 2024. All rights reserved.