首页 > 解决方案 > 如果列表中存在重复键,则删除除另一个值更高的键之外的所有键

问题描述

我是 python 新手,我有一个列表,列表中的每个项目都有 7 个值,我想检查值 1 是否有重复,如果是,则删除除一个之外的所有值,但只有值 7 是浮点数最高.

我无法理解它!

return [(pred, loc, rec, score) if rec else ("unknown", loc, False, 0) for pred, loc, rec, score in zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches, scores)]

我正在检查的值是否重复是 pred,如果 pred 有重复检查最高分并返回其中一个重复项。

我也不想要任何未知数,但我也不确定...

任何帮助将不胜感激,即使我的问题措辞错误并且可以改进。谢谢!

编辑: 下面是返回的列表。如您所见,我有多个ang_h,我只想要得分最高的一个,(最后一个浮点值)

[
    ('ang_h', (401, 2007, 452, 1955), True, 0.41521319721385636),
    ('ang_h', (402, 1821, 438, 1785), True, 0.6270601544247546),
    ('ang_h', (410, 1730, 454, 1687), True, 0.6368848012844088),
    ('ang_h', (418, 2128, 470, 2076), True, 0.5682838831063762),
    ('ang_h', (420, 1015, 463, 971), True, 0.5700311968313606),
    ('ant_s', (1242, 579, 1293, 527), True, 0.40298527559038316),
    ('carl_e', (377, 1941, 420, 1898), True, 0.3242641022125504)
]

编辑#2:

感谢大家的反馈,我学到了很多关于语言的知识!

答案来自@jpp,但已修改为按得分最高的结果排序。

# Put each person into a group by their name in case duplicates found
grouper = groupby(sorted(lst), key=itemgetter(0))

# Get the highest scored location for each person
highest_score = [sorted(list(s), key=itemgetter(-1))[0] for _, s in grouper]

return highest_score

标签: pythonlist

解决方案


我相信这就是你所需要的。您可以对列表进行排序,然后使用itertools.groupby.

from itertools import groupby
from operator import itemgetter

lst = [('ang_h', (401, 2007, 452, 1955), True, 0.41521319721385636),
       ('ang_h', (402, 1821, 438, 1785), True, 0.6270601544247546),
       ('ang_h', (410, 1730, 454, 1687), True, 0.6368848012844088),
       ('ang_h', (418, 2128, 470, 2076), True, 0.5682838831063762),
       ('ang_h', (420, 1015, 463, 971), True, 0.5700311968313606),
       ('ant_s', (1242, 579, 1293, 527), True, 0.40298527559038316),
       ('carl_e', (377, 1941, 420, 1898), True, 0.3242641022125504)]

# sort list by first item and then descending final item
sorted_lst = sorted(lst, key=lambda x: (x[0], -x[-1]))

# group by first item
grouper = groupby(sorted_lst, key=itemgetter(0))

# extract first in each group
res = [list(j)[0] for _, j in grouper]

结果:

[('ang_h', (410, 1730, 454, 1687), True, 0.6368848012844088),
 ('ant_s', (1242, 579, 1293, 527), True, 0.40298527559038316),
 ('carl_e', (377, 1941, 420, 1898), True, 0.3242641022125504)]

推荐阅读