1 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
我建議制作Population一個(gè)生成器功能。請(qǐng)參閱Python yield 關(guān)鍵字解釋:
def Populate(text, c):
for i in range(c):
# compute variation
# [...]
yield variation
創(chuàng)建一個(gè)迭代器并用于next()檢索循環(huán)中的下一個(gè)變體,因此您可以打印每個(gè)變體:
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
根據(jù)評(píng)論編輯:
為了讓我的問(wèn)題簡(jiǎn)單,我沒(méi)有提到Population, 是一個(gè)類 [...]
當(dāng)然Populate can be a class,也是。在這種情況下,您必須實(shí)現(xiàn)該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
通過(guò)創(chuàng)建一個(gè)迭代器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
添加回答
舉報(bào)