Python如何实现列表x去重并累加相同元素对应位置列表y的数值
实现方案
核心逻辑是利用有序字典的键唯一性存储x的元素,同时累加对应位置y的数值,既保留x元素首次出现的顺序,又完成重复元素对应y值的求和。
示例代码(Python 3.7+ 适用,默认字典有序)
输入数据
x = [1,2,3,4,2,3] y = [30, 40, 10, 80, 100,40]
处理逻辑
from collections import defaultdict # 初始化累加字典 sum_dict = defaultdict(int) for xi, yi in zip(x, y): sum_dict[xi] += yi # 拆分得到结果列表 res_x = list(sum_dict.keys()) res_y = list(sum_dict.values())
输出结果
res_x = [1, 2, 3, 4] res_y = [30, 140, 50, 80]
兼容低Python版本方案(3.7以下字典无序场景)
使用OrderedDict保证x元素的顺序和首次出现顺序一致:
from collections import OrderedDict sum_dict = OrderedDict() for xi, yi in zip(x, y): if xi not in sum_dict: sum_dict[xi] = 0 sum_dict[xi] += yi res_x = list(sum_dict.keys()) res_y = list(sum_dict.values())
内容的提问来源于stack exchange,提问作者Pjose123
相关产品推荐
相关产品推荐

