Int*_*rer 0 python iterator loops for-loop while-loop
我有一个用例,我需要重复一些代码块:
我想知道,是否有一些 Python 内置方法可以:
while循环的方式重复for循环的方式重复注意:我知道我可以使用if语句(取决于是否存在上限),并在 afor或whileloop之间切换。我试图不让代码块重复两次,或者它分解为另一个函数。
当前实施
我使用 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.
只需使用count或range,具体取决于上限:
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)