python - 比较和排序两个列表

标签 python list sorting collections duplicates

<分区>

我有以下两个列表:

indexList = [5,3,2,2,7,1]
valueList = [1,2,3,4,5,6]

我想将两者排序在一起,这样输出就是:

indexList = [1,2,2,3,5,7]
valueList = [6,3,4,2,1,5]

然后,我想将缺失的索引及其对应的值填为“0”:

indexList = [1,2,2,3,4,5,6,7]
valueList = [6,3,4,2,0,1,0,5]

最后,我想删除重复的索引并对它们的值求和:

indexList = [1,2,3,4,5,6,7]
valueList = [6,7,2,0,1,0,5]

是否有内置模块来执行此类任务?任何人都可以用智慧指导我吗?

最佳答案

你可以使用 Pandas :

import pandas as pd
indexList = [5,3,2,2,7,1]
valueList = [1,2,3,4,5,6]
s = pd.Series(valueList, index= indexList)
s = s.groupby(s.index).sum().reindex(np.arange(s.index.min(), s.index.max()+1), fill_value=0)
print(s.index.tolist())
print(s.tolist())

输出:

[1, 2, 3, 4, 5, 6, 7]
[6, 7, 2, 0, 1, 0, 5]

详情

  • 创建 pandas series使用 valuesList 作为数据和 indexList 作为 该系列的索引。
  • groupbysum 结合使用,将类似的索引组合在一起,对值求和。
  • 接下来,reindex 从系列索引的 min 到系列 系列索引的max并使用fill_value参数进行填充 缺少具有 0 个值的索引。
  • 打印系列索引tolist
  • 打印系列值 tolist

关于python - 比较和排序两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51988800/

相关文章:

Java:如何按列表的大小对列表列表进行排序?

python - 在 DataFrame 中编码多个标签

bash - 在 csv 文件中输出第一个副本

python - 使用 Django 内联表单集获取 'modelformset_factory without defining ' 字段错误。我究竟做错了什么?

python - 将数据帧的行非 NA 值 "element-wise"与列表相乘

python - 删除任意列包含特定字符串的行

algorithm - 减少正数排序任务以证明 nlogn 复杂度

python - Pygame 按下按键时移动物体

javascript - 如何在点击 react 时为唯一的一个元素切换类

android - 如何使用自定义适配器对 listView 进行排序