有没有一种方法可以在Python中为变量分配条件?
具体来说,我正在编写一个默认情况下是无限的,受选择限制的生成器。这段代码有效,但是重复很丑陋:
def generate(start=0, stop=None):
i = start
if stop == None:
while True:
yield i
i += 1
else:
while i <= stop:
yield i
i += 1
具体来说,我想表达以下内容:
def generate(start=0, stop=None):
i = start
if stop == None:
condition = True
else:
condition = 'i <= stop' # Of course, this will throw an error
while condition:
yield i
i += 1
做到这一点的最佳方法是什么?
谢谢
看来您正在重新实现itertools.count和itertools需要一段时间。
永远计数:
itertools.count()
数到停止:
itertools.takewhile(lambda a: a <= stop, itertools.count())
但这也许是一个愚蠢的例子,也许使条件成为函数就是您要寻找的答案:
def generate(start=0, stop=None):
i = start
if stop == None:
condition = lambda _: True
else:
condition = lambda x: x <= stop
while condition(i):
yield i
i += 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句