本文实例讲述了Python随机数用法。分享给大家供大家参考,具体如下:
1. random.seed(int)
通常是把时间秒数等变化值作为种子值,达到每次运行产生的随机系列都不一样
random.seed(10) print random.random() #0.57140259469 random.seed(10) print random.random() #0.57140259469 同一个种子值,产生的随机数相同 print random.random() #0.428889054675 random.seed() #省略参数,意味着取当前系统时间 print random.random() random.seed() print random.random()
2. random.randint(a,b)
print random.randint(1,10)
3. random.uniform(u,sigma)
随机正态浮点数
print random.uniform(1,5)
4. random.randrange(start,stop,step)
print random.randrange(20,100,5)
5. random.random()
随机浮点数
print random.random()
6. 随机选择字符
随机的选取n个字符
print random.sample('abcdefghijk',3)
print random.choice('abcde./;[fgja13ds2d')
随机选取几个字符,再拼接成新的字符串
print string.join(random.sample('abcdefhjk',4)).replace(" ","")
7.random.shuffle
对list列表随机打乱顺序,也就是洗牌
shuffle只作用于list,对Str会报错比如‘abcdfed',而['1','2','3','5','6','7']可以
item=[1,2,3,4,5,6,7] print item random.shuffle(item) print item item2=['1','7'] print item2 random.shuffle(item2) print item2
PS:这里再为大家提供两款相关在线工具供大家参考使用:
在线随机数字/字符串生成工具:
http://tools.jb51.net/aideddesign/suijishu
高强度密码生成器:
http://tools.jb51.net/password/CreateStrongPassword
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。