我想就地对列表进行排序,并尝试在排序过程中(key功能内)使用列表本身。我发现列表本身似乎是空的。
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
有什么解释吗?
从listobject.c源代码:
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在可以检测到列表在排序过程中发生突变的情况下引发该列表。
ValueError
您可以压缩a并b改为:
a
b
b[:] = [bval for (aval, bval) in sorted(zip(a, b))]