python set 随机,通过Set Python确保迭代的随机顺序

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值