字典无限循环意外退出 [英] Dictionary infinite loop is exiting unexpectedly

查看:83
本文介绍了字典无限循环意外退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了各种在Python中创建无限循环的方法(不是通常的while True),并且想到了这个主意:

I was experimenting with various ways of creating an infinite loop in Python (other than the usual while True), and came up with this idea:

x = {0: None}

for i in x:
    del x[i]
    x[i+1] = None  # Value doesn't matter, so I set it to None
    print(i)

在纸上,我找出了无限循环的方式:

On paper, I traced out the way this would infinitely loop:

  1. 我在字典中遍历键的值
  2. 我删除了该条目.
  3. 循环+ 1中的当前计数器位置将是具有值None的新键,该键将更新字典.
  4. 我输出当前计数器.
  1. I loop through the key's value in the dictionary
  2. I delete that entry.
  3. The current counter position in the loop + 1 will be the new key with value None which updates the dictionary.
  4. I output the current counter.

在我看来,这应该以一种无限循环的方式输出自然数:

This, in my head, should output the natural numbers in a sort of infinite loop fashion:

0
1
2
3
4
5
.
.
.

我认为这个想法很聪明,但是当我在Python 3.6上运行它时,它的输出是:

I thought this idea was clever, however when I run it on Python 3.6, it outputs:

0
1
2
3
4

是的,它在5次迭代后以某种方式停止了.显然,循环的代码块中没有基本条件或哨兵值,那么Python为什么只运行5次此代码?

Yes, it somehow stopped after 5 iterations. Clearly, there is no base condition or sentinel value in the code block of the loop, so why is Python only running this code 5 times?

推荐答案

如果在循环中对其进行了突变,则不能保证将迭代所有dict条目.从文档:

There is no guarantee that you will iterate over all your dict entries if you mutate it in your loop. From the docs:

在添加或删除字典中的条目时迭代视图可能 引发RuntimeError或无法遍历所有条目.

Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.

您可以使用 itertools.count() .例如:

You could create an "enumerated" infinite loop similar to your initial attempt using itertools.count(). For example:

from itertools import count

for i in count():
    print(i)
    # don't run this without some mechanism to break the loop, i.e.
    # if i == 10:
    #     break

# OUTPUT
# 0
# 1
# 2
# ...and so on

这篇关于字典无限循环意外退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆