python - python在for循环之前卡住列表吗?

标签 python for-loop

假设我有一个列表 l 和一个线程 t1 永远迭代 l:

while True:
    for i in l:
        #do something

和另一个线程 t2 随机修改或删除 l 中的成员。

删除后会发生什么? t1 是否在当前循环中检测到它?

更新:

  1. 我所说的卡住是指 t1 获取 l 的副本。 t2 可以修改 l 为 当然

  2. 引用文档或简单但有说服力的代码片段是 欢迎。

最佳答案

没有。该列表未卡住 - 您的迭代器不会在引发异常的意义上“中断”。相反,它会在列表中继续前进,结果可能会令人惊讶。

考虑这段代码(ideone 中的代码片段:http://ideone.com/0iMao):

l = list(range(10))
for i in l:
    print i
    try:
        del l[i]
    except (RuntimeError,IndexError), e:
        print e

print l

它产生这个输出:

0
2
4
5
7
list assignment index out of range
9
list assignment index out of range
[1, 2, 4, 5, 7, 9]

这可能不是您想要或期望的,尽管它显然定义明确:http://docs.python.org/reference/compound_stmts.html#the-for-statement .

相反,您可以锁定列表或复制一份。请注意,iter(l) 不会在内部进行复制,并且与直接遍历列表具有相同的效果。

关于python - python在for循环之前卡住列表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9515364/

相关文章:

c++ - For循环跳过getline C++

arrays - 如何从两个元素列表中获取一个元组

javascript - 具有多个条件的 If 子句

python - 您必须使用 dtype float 和 shape [2,2] 为占位符张量 'Placeholder' 提供一个值

python列表从for循环到一个列表

python - Django:标签中的For循环显示不同的信息

python - 如何使用 python 加密/解密任意长度的二进制文件?

python - Coverage 是否提供自己版本的 Nose 插件?

python - 如何使用一个 SQLAlchemy 模型保存到两个表

Python gevent+瓶子。查询 API。如何使用gevent防止超时锁?