1 回答
TA贡献1946条经验 获得超3个赞
我建议制作Population一个生成器功能。请参阅Python yield 关键字解释:
def Populate(text, c):
for i in range(c):
# compute variation
# [...]
yield variation
创建一个迭代器并用于next()检索循环中的下一个变体,因此您可以打印每个变体:
populate_iter = Populate(text, 1000)
final_variation = None
while not done:
next_variation = next(populate_iter, None)
if next_variation :
final_variation = next_variation
# print current variation
# [...]
else:
done = True
根据评论编辑:
为了让我的问题简单,我没有提到Population, 是一个类 [...]
当然Populate can be a class,也是。在这种情况下,您必须实现该object.__iter__(self)方法。例如:
class Populate:
def __init__(self, text, c):
self.text = text
self.c = c
def __iter__(self):
for i in range(self.c):
# compute variation
# [...]
yield variation
通过创建一个迭代器iter()。例如:
populate_iter = iter(Populate(text, 1000))
final_variation = None
while not done:
next_variation = next(populate_iter, None)
if next_variation :
final_variation = next_variation
# print current variation
# [...]
else:
done = True
添加回答
举报