Python如何制作可以是“for”或“while”的循环,取决于是否存在上限

Int*_*rer 0 python iterator loops for-loop while-loop

我有一个用例,我需要重复一些代码块:

  • 有时我需要重复代码块有限次数
  • 有时我需要无限期地重复代码块。

我想知道,是否有一些 Python 内置方法可以:

  • 没有提供限制 --> 代码块通过类似while循环的方式重复
  • 提供的限制 --> 代码块通过类似for循环的方式重复

注意:我知道我可以使用if语句(取决于是否存在上限),并在 aforwhileloop之间切换。我试图不让代码块重复两次,或者它分解为另一个函数。


当前实施

我使用 Python 3.8.2编写了以下有缺陷的(见下文)for_while_hybrid.py

from typing import Iterator


def iter_for_while(num_yield: int = None) -> Iterator[int]:
    """Generate an incrementing counter.

     This enables one to make a for loop or a while loop, depending on args.

    Args:
        num_yield: Number of times to yield.
            If left as None, the generator makes a while loop
            If an integer, the generator makes a for loop

    """
    counter = 0
    condition = True if num_yield is None else counter < num_yield
    while condition:
        yield counter
        counter += 1
        if num_yield is not None:
            condition = counter < num_yield


upper_limit = 5
for _ in iter_for_while(upper_limit):
    print("Some code block")  # Run 5 times

for _ in iter_for_while():
    print("Some code block")  # Run infinitely
Run Code Online (Sandbox Code Playgroud)

这个实现有效。

缺点是,如果运行很长时间,我担心counter会占用大量内存,或者最终会达到最大值。我的电脑是 64 位的,所以sys.maxsize = 2 ** 63 - 1 = 9,223,372,036,854,775,807.

che*_*ner 6

只需使用countrange,具体取决于上限:

from itertools import count


def iter_for_while(bound=None):
    return count() if bound is None else range(bound)
Run Code Online (Sandbox Code Playgroud)

  • 这没有什么实际区别。如果循环运行十亿次,计数器的大小将从 24 字节增长到 28 字节。一万亿次,计数器仍然只有 32 个字节。如果该评论者确实看到了内存问题,那也不是来自柜台。 (2认同)