首页 > 解决方案 > 类似于 group by for 列表的操作

问题描述

我有 id 和分数列表:

ids=[1,2,1,1,3,1]
scores=[10,20,10,30,40,10]

我想从列表 id 中删除重复项,以便相应地总结分数。这与 groupby.sum() 在使用数据帧时所做的非常相似。

所以,作为我期望的输出:

ids=[1,2,3]
scores=[60,20,40]

我使用以下代码,但它不适用于所有情况:

for indi ,i in enumerate(ids):
     for indj ,j in enumerate(ids):
           if(i==j) and (indi!=indj):
                  del ids[i]
                  scores[indj]=scores[indi]+scores[indj]
                  del scores[indi]

标签: pythonlist

解决方案


您可以创建一个字典,使用idsscores作为元素的键id和值作为与元素对应的元素列表id,您可以对这些值求和,并获得新的idscores列表

from collections import defaultdict

ids=[1,2,1,1,3,1]
scores=[10,20,10,30,40,10]

dct = defaultdict(list)

#Create the dictionary of element of ids vs list of elements of scores
for id, score in zip(ids, scores):
    dct[id].append(score)

print(dct)
#defaultdict(<class 'list'>, {1: [10, 10, 30, 10], 2: [20], 3: [40]})

#Calculate the sum of values, and get the new ids and scores list
new_ids, new_scores = zip(*((key, sum(value)) for key, value in dct.items()))

print(list(new_ids))
print(list(new_scores))

输出将是

[1, 2, 3]
[60, 20, 40]

推荐阅读