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

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

问题描述

我可以在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_SET_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天全站免登陆