如何在Python中获取生成器的新输入而不创建新的生成器
我尝试编写代码,通过使用yield语句获取一个列表并生成所有这些转换 问题是,当我想使用send函数向生成器获取新输入时,我会继续获取旧输入如何在Python中获取生成器的新输入而不创建新的生成器,python,yield,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'])
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')
在不创建新生成器的情况下,如何清空置换列表并重复排序置换列表步骤?为什么不创建一个类型为
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')
您在对答案的评论中提到需要使用
send
。你能解释一下你为什么要在这里这么做吗?这是一项家庭作业,目的是教你send
如何工作?