我可以在 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具有相同的范围
。为什么函数 m
将 b
打印为 []
?
最佳答案
查看 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/