小编典典

排序过程中列表似乎为空

python

我想就地对列表进行排序,并尝试在排序过程中(key功能内)使用列表本身。我发现列表本身似乎是空的。

a = [1,4,5,3,2,6,0]
b = ['b', 'e', 'f', 'd', 'c', 'g', 'a']
b.sort(key=lambda x: a[b.index(x)])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
ValueError: 'b' is not in list

所以我尝试了:

def f(x):
  print "FOO:", x, b
  return b.index(x)

b.sort(key=f)

并得到

FOO: b []
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in f
ValueError: 'b' is not in list

有什么解释吗?


阅读 310

收藏
2021-01-20

共1个答案

小编典典

listobject.c源代码

/* The list is temporarily made empty, so that mutations performed
 * by comparison functions can't affect the slice of memory we're
 * sorting (allowing mutations during sorting is a core-dump
 * factory, since ob_item may change).
 */

并从Mutable Sequence
Types文档中

CPython实现细节 :在对列表进行排序时,尝试使列表变异甚至检查的效果是不确定的。Python
2.3及更高版本的C实现使列表在整个持续时间内都显示为空,并ValueError在可以检测到列表在排序过程中发生突变的情况下引发该列表。

您可以压缩ab改为:

b[:] = [bval for (aval, bval) in sorted(zip(a, b))]
2021-01-20