排序过程中列表似乎为空[重复]
这个问题已经在这里有了答案 :
在排序时访问列表 (2个答案)
6年前关闭。
我想就地对列表进行排序,并尝试在排序过程中(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
有什么解释吗?
-
/* 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). */
CPython实现细节 :在对列表进行排序时,尝试使列表变异甚至检查的效果是不确定的。Python
2.3及更高版本的C实现使列表在整个持续时间内都显示为空,并ValueError
在可以检测到列表在排序过程中发生突变的情况下引发该列表。您可以压缩
a
并b
改为:b[:] = [bval for (aval, bval) in sorted(zip(a, b))]