PYTHON:在每个项的第一个索引中查找重复的元素,并基于第二个索引删除项

2024-04-29 07:39:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个二维数组,存储不同的人的名字和分数。程序应该对数组进行排序,如果每个人都有多个分数,则应该删除除最高分数之外的所有分数。你知道吗

scores = [["Alexander", 7], ["Lucy", 4], ["Kieran", 5], ["Alexander", 4]]

应该删除[“Alexander”,4],因为数组中有两个名为“Alexander”的项,4是其中的最低分数。你知道吗


Tags: 程序排序数组名字分数alexanderscoreslucy
1条回答
网友
1楼 · 发布于 2024-04-29 07:39:22

这应该是可行的,尽管可能有一个现成的模块做得更好。你知道吗

我假设你练习的重点是学习变量类型和max()函数。你知道吗

def choose_highest(arr):
    namescores = dict()
    for person, score in arr:
         namescores.setdefault(person, score)
         namescores[person] = max(namescores[person], score)
    return list(namescores.items())

或者,如果要在列表中包含列表,请使用此返回:

return [[key, value] for key, value in namescores.items()]

相关问题 更多 >