小编典典

排序时访问列表

python

在列表中进行排序时,我可以访问列表吗? 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

这回来

b [] check this
e [] check this
f [] check this
d [] check this
c [] check this
g [] check this
a [] check this

请注意,列表的各个项目b都发送给function
m。但是在mlist处b为空,但是可以看到该变量f,其作用域与list相同b。为什么功能m打印b[]


阅读 191

收藏
2020-12-20

共1个答案

小编典典

查看源代码(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;

注释说明了一切:开始排序时,列表将被清空。好吧,在外部观察者的眼中,它是“空的”。

我非常喜欢“堆芯工厂”一词。


还比较:

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
2020-12-20