Ensuring random order for iteration over Set Python

不打扰是莪最后的温柔 提交于 2019-12-11 10:48:52

问题


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?


回答1:


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



回答2:


You can use random.shuffle to shuffle your set:

>>> from random import shuffle
>>> a = set([1,2,3,4,5])
>>> b = list(a)
>>> shuffle(b)
>>> b
[4, 2, 1, 3, 5]
>>> 


来源:https://stackoverflow.com/questions/31598562/ensuring-random-order-for-iteration-over-set-python

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