问题
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