首页 > 解决方案 > 如何在不创建新生成器的情况下在 Python 中获取生成器的新输入

问题描述

我尝试编写获取列表并使用 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')

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

标签: pythonyield

解决方案


为什么不创建一个新的类型对象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')

推荐阅读