如何在不创建新生成器的情况下使用Python将新输入获取到生成器 [英] How to get new input to generator in Python without create a new generator
本文介绍了如何在不创建新生成器的情况下使用Python将新输入获取到生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试编写获取列表并使用yield语句生成所有这些转换的代码.
I try to write code that gets a list and generates all of this transformations by using yield statement.
问题是,当我想使用send函数将新的输入获取到生成器时,我会继续获取旧的输入.
The problem is when I want to get new input to generator by using send function, I continue to get the old input.
def permute(items):
permutations = [x for x in itertools.permutations(items)]
permutations.sort()
for n in permutations:
yield (n)
g = permute(['b','a','c'])
print(next(g)) #('a', 'b', 'c')
print(next(g)) #('a', 'c', 'b')
g.send(['e','q','c'])
print(next(g)) #('b', 'c', 'a') need to be ('c', 'e', 'q')
如何在不创建新生成器的情况下清空排列列表并重复排列排列列表的步骤?
How can I empty the permutation list and repeat to sorting permutations list step without create a new generator?
推荐答案
为什么不仅仅创建一个permute
类型的新对象并使用它
Why not just create a new object of type permute
and use it
import itertools
def permute(items):
permutations = [x for x in itertools.permutations(items)]
permutations.sort()
for n in permutations:
yield (n)
g = permute(['b','a','c'])
print(next(g)) #('a', 'b', 'c')
print(next(g)) #('a', 'c', 'b')
g = permute(['e','q','c'])
print(next(g)) #('b', 'c', 'a') need to be ('c', 'e', 'q')
#I get ('c', 'e', 'q')
这篇关于如何在不创建新生成器的情况下使用Python将新输入获取到生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文