python - 在排序时访问列表

标签 python list sorting 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

返回

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 打印为 []

最佳答案

查看 source code (对于 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_SET_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

关于python - 在排序时访问列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22678141/

相关文章:

Python:如何将从列表中提取的数据保存在元组(名称,num1,num2)中?

sorting - 在 Cassandra 中以不同方式或顺序查询表

python - 字符串模块与str的关系

java - 如何将overlayItem 对象添加到数组中?

python - ITK 4.0 的构建和安装有完整的指南吗?

list - 请解释一下这段序言代码的作用

c# - LINQ OrderBy 使用真正的 ASCII 排序忽略大小写

c - 升序冒泡排序问题

python - 如何捕获 Python 解释器的输出并在 Text 小部件中显示?

python - 如何在 10 秒后强制用户输入