在C++
中,我们可以像for(;;)
一样编写一个无限的for循环。在Python中有没有类似这样的语法来写一个无限的for循环?
注意:我知道如果我写for i in range(a_very_big_value)
,它可能会运行无穷大。我正在寻找一种简单的语法,比如C++
或任何其他用Python语言编写infinite for loop
的技巧。
发布于 2018-06-22 12:24:38
是的,这是可能的。
使用while
循环:
while True:
...
使用for
循环(仅用于踢球):
from itertools import cycle
for _ in cycle(range(1)):
...
cycle
无限期返回1
。
在任何一种情况下,都要由您来实现您的循环逻辑,使其最终终止。最后,如果你想实现一个execute-until-__循环,你应该坚持使用while True
,因为这是惯用的方式。
发布于 2018-06-22 12:26:06
好的,给您:
for i in __import__("itertools").count():
pass
无限迭代器部分取自this answer.,不过,如果你仔细考虑一下,while循环看起来要好得多。
while True:
pass
发布于 2018-06-22 12:24:33
您可以使用:
while True:
# Do stuff here
https://stackoverflow.com/questions/50980635
复制相似问题