I am iterating over a Set in Python. In my application I prefer that the iteration be in a random order each time. However what I see is that I get the same order each time I run the program. This isn't fatal but is there a way to ensure randomized iteration over a Set?
解决方案
Use random.shuffle on a list of the set.
>>> import random
>>> s = set('abcdefghijklmnopqrstuvwxyz')
>>> for i in range(5): #5 tries
l = list(s)
random.shuffle(l)
print ''.join(l) #iteration
nguoqbiwjvelmxdyazptcfhsrk
fxmaupvhboclkyqrgdzinjestw
bojweuczdfnqykpxhmgvsairtl
wnckxfogjzpdlqtvishmeuabry
frhjwbipnmdtzsqcaguylkxove