我正在尝试按照 priority 中的顺序对 todo 进行排序
>>> todo
['see doctor', 'do assignment', 'pay rent', 'check bank account', 'clean room']
>>> priority
[3, 4, 1, 2, 5]
>>> todo.sort(key=lambda x: priority[todo.index(x)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
ValueError: 'see doctor' is not in list
当我尝试像这样对 todo 进行排序时,为什么会出现此错误?
尽管与 sorted 一起工作:
>>> sorted(todo, key=lambda x: priority[todo.index(x)])
['pay rent', 'check bank account', 'see doctor', 'do assignment', 'clean room']
为什么它适用于 sorted 但不适用于 sort?
请您参考如下方法:
好吧,你可以简单地 zip() 2 列表,然后使用 sorted() 根据 priority 对其进行排序.
>>> todo = ['see doctor', 'do assignment', 'pay rent', 'check bank account', 'clean room']
>>> priority = [3, 4, 1, 2, 5]
>>> [y for (x,y) in sorted(zip(priority, todo))]
['pay rent', 'check bank account', 'see doctor', 'do assignment', 'clean room']
编辑:您收到错误 ValueError: 'see doctor' is not in list 的原因是因为使用 list.sort() 之间存在差异。和内置函数 sorted() .
sorted()returns a new sorted list, leaving the original list unaffected.list.sort()sorts the list in-place, mutating the list indices.
可以引用这个answer有关差异的更多说明。
如果您引用 source code for list.sort() (listsort() 函数),您会注意到函数中的注释 -
The list is temporarily made empty, so that mutations performed by comparison functions can't affect the slice of memory we're sorting.
因此,当 lambda 函数执行时,它会尝试在列表中找到 'see doctor' 的索引(来自 todo.index(x))。但由于列表为空,它返回 ValueError: 'see doctor' is not in list。
sorted() 不会抛出此错误,因为它会初始化一个新的空列表,然后将字符串附加到新创建的列表中而不修改给定列表(即 todo).
list.sort() 的源代码和 sorted() .
