排序(键=函数)不起作用,但排序(iterable,键=函数)起作用

2024-09-24 22:29:58 发布

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

我想根据元素第一次出现的索引对列表进行排序

例如:

l=[3,2,1,2,3,1,4]
output=[3,3,2,2,1,1,4]

我尝试了以下代码

def sortfunc(idx:int):
    return l.index(idx)
print(sorted(l,key=sortfunc))

它运行得很好,但当我尝试l.sort(key=sortfunc)它的提升ValueError

>>> l=[3,2,1,2,3,1,4]
>>> l.sort(key=sortfunc)
Traceback (most recent call last):
  File "<pyshell#63>", line 1, in <module>
    l.sort(key=sortfunc)
  File "<pyshell#45>", line 2, in sortfunc
    return l.index(idx)
ValueError: 3 is not in list
>>> 

我错过了什么


Tags: keyin元素列表outputindexreturn排序