Python: How To Append Generator Iteration Values To A List
I have a simple generator to give me permutations of a set of coordinates. I wish to save each new permutation to an element in an array using the code below: import random def po
Solution 1:
Your generator does not yield new lists, it yields the same list over and over again. When you append that yielded reference to a
you only get to see the same original list, in it's most recently shuffled form, over and over again.
Yield a copy instead:
def poss_comb(coord):
coord = coord[:] # use a local copy of the list
random.shuffle(coord)
yield coord
or create a random sort instead of using inplace shuffling with the sorted()
function:
def poss_comb(coord):
yield sorted(coord, key=lambda k: random.random())
Post a Comment for "Python: How To Append Generator Iteration Values To A List"