分类时访问列表
我可以在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 。但是在m
list b
是空的,但是它可以看到变量f
,其范围与List b 。为什么功能
m
打印b
为[]
?
Can I access a list while it is being sorted in the 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
this returns
b [] check this
e [] check this
f [] check this
d [] check this
c [] check this
g [] check this
a [] check this
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 []
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 source code>其他实现的行为不同)脚本的奇怪输出变得显而易见:
评论说明了一切:开始分类时,列表被清空。好吧,它在外部观察者的眼中是“空的”。
我非常喜欢“ Core-Dump Factory”一词。
也比较:
Looking at the source code (of CPython, maybe different behaviour for other implementations) the strange output of your script becomes obvious:
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".
Compare also:
这是您一般不能依靠的东西 - 不仅是列表 - 除非您使用明确的方法的文档。访问中间状态的对象 - 即启动了一些迭代后,但是在完成之前,它是一个并发代码大量运行的问题。您已经发现了一个罕见的非交通案例,但是建议是相同的:避免这种情况。中间状态不能保证对您有意义,并且不能保证根据该对象的规则(当它被称为“不一致”状态时)是“有效的”状态。
This is something you can't rely on in general - not just for lists - unless the documentation for the method you're using explicitly says otherwise. Accessing an object in an intermediate state - ie, after some iteration has been started, but before it has been finished - is a problem that concurrent code runs into a lot. You've found a rare non-concurrent case of it, but the advice is the same: avoid this situation. The intermediate state is not guaranteed to be meaningful to you, and is not guaranteed to be a "valid" state according to the rules of that object (when it tends to be called an "inconsistent" state).