排序过程中列表似乎为空 [英] List appears to be empty during sorting

查看:57
本文介绍了排序过程中列表似乎为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wanted to sort a list in-place and tried using the list itself during the sorting (within a key function). I found out that the list itself appears to be empty in there.

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源代码:

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

CPython implementation detail: While a list is being sorted, the effect of attempting to mutate, or even inspect, the list is undefined. The C implementation of Python 2.3 and newer makes the list appear empty for the duration, and raises ValueError if it can detect that the list has been mutated during a sort.

您可以改为压缩ab:

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

这篇关于排序过程中列表似乎为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆