通过Set Python确保迭代的随机顺序 [英] Ensuring random order for iteration over Set Python

查看:282
本文介绍了通过Set Python确保迭代的随机顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在迭代Python中的Set。在我的应用程序中,我更喜欢每次迭代都是随机顺序。但是我看到的是每次运行程序时都会得到相同的顺序。这不是致命的,但有没有办法确保Set上的随机迭代?

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?

推荐答案

使用 random.shuffle 在该列表中。

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

这篇关于通过Set Python确保迭代的随机顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆