Python在排序时访问列表

nr.*_*r.o 15 python sorting list python-internals

我可以在列表中进行排序时访问列表吗? list.sort()

b = ['b', 'e', 'f', 'd', 'c', 'g', 'a']
f = 'check this'

def m(i):
    print i, b, f
    return None

b.sort(key=m)
print b
Run Code Online (Sandbox Code Playgroud)

这回来了

b [] check this
e [] check this
f [] check this
d [] check this
c [] check this
g [] check this
a [] check this
Run Code Online (Sandbox Code Playgroud)

请注意,列表的各个项目将b发送到功能m.但是在m列表中b是空的,但它可以看到变量f,其范围与列表相同b.为什么功能m打印b[]

Hyp*_*eus 13

查看源代码(CPython,可能是其他实现的不同行为),脚本的奇怪输出变得明显:

/* 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).
*/
saved_ob_size = Py_SIZE(self);
saved_ob_item = self->ob_item;
saved_allocated = self->allocated;
Py_SIZE(self) = 0;
Run Code Online (Sandbox Code Playgroud)

评论说明了一切:当您开始排序时,列表将被清空.嗯,它在外部观察者眼中是"空的".

我非常喜欢"核心转储工厂"这个词.


比较还:

b = ['b','e','f','d','c','g','a']
f = 'check this'


def m(i):
    print i, b, f
    return None

b = sorted(b, key= m)
print b
Run Code Online (Sandbox Code Playgroud)

  • 还有一个特定的[文档中提到](http://docs.python.org/2/library/stdtypes.html#mutable-sequence-types) 这种行为。请参阅可变序列类型下的注释 10。 (2认同)