python - 从字典列表中删除重复键,仅保留值最大的键值

标签 python algorithm

来自类似的列表:

mylist = [{'x':2020 , 'y':20},{'x':2020 , 'y':30},{'x':2021 , 'y':10},{'x':2021 , 'y':5}]

我想让所有 'x' 都是唯一的,并且 'y' 是最大的,而 'x' 是相同的。

我正在尝试将输出设为:

mylist_unique =  [{'x':2020 , 'y':30},{'x':2021 , 'y':10}]

我以一种非常幼稚的方式实现了它:

res =[]
temp = {}
print(len(temp))

for i in range(len(mylist)):
    print(mylist[i])
    for k,v in mylist[i].items():
        print(mylist[i]['x'],temp.keys(),mylist[i]['y'])
        if mylist[i]['x'] not in temp.keys() or mylist[i]['y'] > (temp[mylist[i]['x']]) :
            print(k)
            temp.update({mylist[i]['x']:mylist[i]['y']})

print(temp)
for k,v in temp.items():
    res.append({'x':k,'y':v})
print(res)

最佳答案

您可以通过 itertools.groupby 使用字典理解:

from itertools import groupby

mylist = [{'x': 2020, 'y': 20}, {'x': 2020, 'y': 30}, {'x': 2021, 'y': 10}, {'x': 2021, 'y': 5}]

mylist_unique = [{'x': key, 'y': max(item['y'] for item in values)}
                 for key, values in groupby(mylist, lambda dct: dct['x'])]
print(mylist_unique)

这产生

[{'x': 2020, 'y': 30}, {'x': 2021, 'y': 10}]

关于python - 从字典列表中删除重复键,仅保留值最大的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63934090/

相关文章:

python - 将 DatetimeIndex 转换为日期时间

algorithm - 检查一个单词是否由一个或多个串联的字典单词组成

algorithm - 什么算法可用于以相当优化的方式将不同大小的矩形打包成尽可能小的矩形?

python - 返回修改后的类和使用 type() 的区别

python - 如何在 Python 中随机返回列表中最大元素之一的索引?

python - 使用 Pandas 将 suds 对象转换为数据框

python - Python中的模糊字符串匹配

algorithm - 遗传算法中交叉的效率

ios - 比较 Swift 中两个元组列表的重复项

python - Pymodbus TCP `read_holding_registers` 返回陈旧/旧数据