How to get new input to generator in Python without create a new generator

这一生的挚爱 提交于 2020-01-16 07:36:08

问题


I try to write code that gets a list and generates all of this transformations by using yield statement.

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?


回答1:


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


来源:https://stackoverflow.com/questions/55966064/how-to-get-new-input-to-generator-in-python-without-create-a-new-generator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!