代码之家  ›  专栏  ›  技术社区  ›  Taohidul Islam

Python中循环的无穷大,如C++

  •  0
  • Taohidul Islam  · 技术社区  · 6 年前

    C++ 我们可以写一个无限for循环 for(;;) . 在python中有没有类似的语法来编写无限for循环?

    注:我知道如果我写 for i in range(a_very_big_value) 然后它可能会无限延伸。我正在搜索一个简单的语法,比如 C++ 或其他写作技巧 infinite for loop 用python。

    5 回复  |  直到 6 年前
        1
  •  4
  •   abarnert    6 年前

    蟒蛇 for 语句是“for each”循环(类似于 range-for 在C++ 11和以后,不是C风格的“计算”循环。

    但请注意,在c中, for (;;) 做同样的事情 while (1) . 和蟒蛇的 while 循环基本上和C的一样,有几个额外的铃铛和哨子。事实上,惯用的循环方式是:

    while True:
    

    如果你真的想写 对于 循环是永远的,你需要无限长的Iterable。您可以从标准库中获取一个:

    for _ in itertools.count():
    

    或者你自己写一封:

    def forever():
        while True:
            yield None
    
    for _ in forever():
    

    不过,这和 (;) ,因为它是一个for-each循环。


    1。 while 1: 曾经是一种常见的选择。在较旧版本的python中速度更快,尽管在当前版本中不是这样,有时这很重要。

    2。当然,关键是 count 不仅仅是永远的,而是永远的数数。例如,如果 enumerate 不存在,你可以把它写成 zip(itertools.count(), it) .

        2
  •  3
  •   cs95 abhishek58g    6 年前

    是的,这是可能的。

    用一个 while 循环:

    while True:
       ...
    

    用一个 for 循环(仅用于踢腿):

    from itertools import cycle    
    for _ in cycle(range(1)):
        ...
    

    这个 cycle 收益率 1 无限期。

    无论是哪种情况,都取决于您以最终终止的方式实现循环逻辑。最后,如果要实现execute until-\uuuuuu循环,应该坚持 while True ,因为这是惯用的方法。

        3
  •  2
  •   Chayan Mistry    6 年前

    我找到了答案 here here

    使用 itertools.count :

    import itertools
    for i in itertools.count():
        if there_is_a_reason_to_break(i):
            break
    

    在Python 2xRange()中,Sy.MaxTt有限,这可能是最实用的目的:

    import sys
    for i in xrange(sys.maxint):
        if there_is_a_reason_to_break(i):
            break
    

    在python3中,range()可以高得多,但不是无限的:

    import sys
    for i in range(sys.maxsize**10):  # you could go even higher if you really want
        if there_is_a_reason_to_break(i):
            break
    

    所以最好用 count()


    也可以通过改变正在迭代的列表来实现这一点,例如:

    l = [1]
    for x in l:
        l.append(x + 1)
        print(x)
    
        4
  •  1
  •   mustachioed    6 年前

    是的,给你:

    for i in __import__("itertools").count():
        pass
    

    无限迭代器部分取自 this answer. 不过,如果你真的考虑过的话,一个while循环看起来好多了。

    while True:
        pass
    
        5
  •  0
  •   sleblanc    6 年前

    你可以使用:

    while True:
        # Do stuff here