python - 类似于 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]
解决方案
您可以创建一个字典,使用ids
和scores
作为元素的键id
和值作为与元素对应的元素列表id
,您可以对这些值求和,并获得新的id
和scores
列表
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]
推荐阅读
- mysql - 在 sql 输出中打印一个字符
- windows - 术语“Get-CMApplication”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称
- if-statement - 在 awk 中使用 if 条件
- dart - 不使用显式类型的理由是什么?
- r - 如何根据数据框中的多列组合两行?
- android - Android Seekbar 双向数据绑定
- nuxt.js - Vuetify:为 v-select 编辑 no-data-text prop 或 no-data 插槽似乎没有任何效果
- abap - 使用哪个 BAPI 来更新 ADRC 表?
- python - Python中的N个连续值屏幕
- kotlin - android mvvm onclick 事件,如何实时数据?