列表在排序期间显示为空

时间:2014-03-27 12:21:56

标签: python list sorting

我希望对列表进行排序,并尝试在排序期间使用列表本身(在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

对此有何解释?

1 个答案:

答案 0 :(得分:11)

来自listobject.c source code

/* 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 documentation

  

CPython实现细节:在对列表进行排序时,尝试变异甚至检查列表的效果是不确定的。 Python 2.3及更新版本的C实现使得列表在持续时间内显示为空,如果它可以检测到列表在排序期间已被突变,则会引发ValueError

您可以改为ab

b[:] = [bval for (aval, bval) in sorted(zip(a, b))]