我有一个程序,该程序从用户处获取输入,并使用Population()
函数显示输入的多种变化。 store_fit
函数将这些不同的变体添加到列表中,然后将其删除,因此列表一次只能填充一个变体。
我希望能够从列表中获取变体并使用它来更新我的文字。但是,我的程序仅在Population
函数完成后才更新文本。如何运行Population
函数并同时更新文本?
代码:
fit = []
...
def store_fit(fittest): # fittest is each variation from Population
clear.fit()
fit.append(fittest)
...
pg.init()
...
done = False
while not done:
...
if event.key == pg.K_RETURN:
print(text)
target = text
Population(1000) #1000 variations
store_fit(value)
# I want this to run at the same time as Population
fittest = fit[0]
...
top_sentence = font.render(("test: " + fittest), 1, pg.Color('lightskyblue3'))
screen.blit(top_sentence, (400, 400))
答案 0 :(得分:2)
我建议使Population
成为生成器函数。参见The Python yield keyword explained:
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