我有一个用例,需要重复一些代码块:
有时,我需要重复代码块--有限数量的times
我想知道,是否有内置Python的方式:
while循环for循环之类的东西重复的。
注意:我知道我可以使用if语句(取决于是否存在上限),并在for或while循环之间切换。我试图不让代码块重复两次,否则它会被分解成另一个函数。
当前实现
我使用Python3.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这种实现是可行的。
缺点是,如果运行很长一段时间,我担心counter会占用大量内存,或者最终会耗尽内存。我的电脑是64位,所以sys.maxsize = 2 ** 63 - 1 = 9,223,372,036,854,775,807.
发布于 2020-06-17 18:25:18
使用with循环,但是您可以说then < Y:做一些事情,然后X += 1,这意味着您可以控制它与X重复多少次,或者如果您想无限地使用它,就不要说X+1。
发布于 2020-06-17 18:25:27
只需使用count或range,取决于上限:
from itertools import count
def iter_for_while(bound=None):
return count() if bound is None else range(bound)https://stackoverflow.com/questions/62435739
复制相似问题