如何在不创建新生成器的情况下使用Python将新输入获取到生成器

时间:2019-05-03 08:32:58

标签: python yield

我尝试编写获取列表并使用yield语句生成所有转换的代码。

问题是当我想通过使用send函数将新的输入获取到生成器时,我继续获取旧的输入。

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')

如何在不创建新生成器的情况下清空排列列表并重复排列排列列表的步骤?

2 个答案:

答案 0 :(得分:1)

为什么不只是创建permute类型的新对象并使用它

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')

答案 1 :(得分:0)

要使用send,您需要进行一次赋值something = yield something_else,并检查something的值:将调用Nonenext(g)并如果调用了value,它将有g.send(value)

这是一种可能的解决方案:

import itertools

def permute(items):
    permutations = [x for x in itertools.permutations(items)]
    permutations.sort()
    it = iter(permutations)
    while True:
        new_items = yield next(it)
        if new_items is not None:
            yield None  # it is yielded for g.send()
            permutations = [x for x in itertools.permutations(new_items)]
            permutations.sort()
            it = iter(permutations)

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)) #('c', 'e', 'q')