排序时访问列表 [英] Accessing the list while being sorted

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

问题描述

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的各个项目被发送到功能m.但是在m处,列表b为空,但是可以看到变量f,其作用域与列表b相同.为什么功能mb打印为[]?

Note that individual items of list b is sent to function m. But at m the list b is empty, however it can see the variable f, which has same scope as list b. Why does function m print b as []?

推荐答案

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

Looking at the source code (of CPython, maybe different behaviour for other implementations) the strange output of your script becomes obvious:

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

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

The comment says it all: When you begin sorting, the list is emptied. Well, it is "empty" in the eye of an external observer.

我很喜欢堆芯工厂"一词.

I quite like the term "core-dump factory".

还比较:

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

这篇关于排序时访问列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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