假设我有一个这样的列表:
[[0.5, 5281],
[0.7, 6597],
[0.7, 6716],
[0.7, 6902],
[0.7, 5704]]
我想对具有相同第一个元素的元素求和,得到类似的结果:
[[0.5, 5281],
[0.7, the result of 6597+6716+..+5704]].
在 Python 中有没有一种简单的方法可以做到这一点?
最佳答案
使用 pandas
怎么样?
(我想你还是用 pandas
读取了你的数据库)
import pandas as pd
original_list = [
[0.5, 5281],
[0.7, 6597],
[0.7, 6716],
[0.7, 6902],
[0.7, 5704]]
df = pd.DataFrame(original_list, columns=['col1', 'col2'])
df_out = df.groupby('col1').sum()
print(df_out)
结果:
col2
col1
0.5 5281
0.7 25919
关于python - 在 Python 上根据相等条件添加列表的第二个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70531149/