本文实例讲述了Python随机数用法。分享给大家供大家参考,具体如下:
[b]1. random.seed(int)[/b]
给随机数对象一个种子值,用于产生随机序列。
对于同一个种子值的输入,之后产生的随机数序列也一样。
通常是把时间秒数等变化值作为种子值,达到每次运行产生的随机系列都不一样
seed() 省略参数,意味着使用当前系统时间生成随机数
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()
[b]2. random.randint(a,b)[/b]
返回指定范围的一个随机整数,包含上下限
print random.randint(1,10)
[b]3. random.uniform(u,sigma)[/b]
随机正态浮点数
print random.uniform(1,5)
[b]4. random.randrange(start,stop,step)[/b]
按步长随机在上下限范围内取一个随机数
print random.randrange(20,100,5)
[b]5. random.random()[/b]
随机浮点数
[b]6. 随机选择字符[/b]
随机的选取n个字符
print random.sample('abcdefghijk',3)
随机的选取一个字符
print random.choice('abcde./;[fgja13ds2d')
随机选取几个字符,再拼接成新的字符串
print string.join(random.sample('abcdefhjk',4)).replace(" ","")
[b]7.random.shuffle[/b]
对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','2','3','5','6','7']
print item2
random.shuffle(item2)
print item2
[b]PS:这里再为大家提供两款相关在线工具供大家参考使用:[/b]
[b]在线随机数字/字符串生成工具:
[/b][url=http://tools.jb51.net/aideddesign/suijishu]http://tools.jb51.net/aideddesign/suijishu[/url]
[b]高强度密码生成器:
[/b][url=http://tools.jb51.net/password/CreateStrongPassword]http://tools.jb51.net/password/CreateStrongPassword[/url]
更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/648.htm]Python Socket编程技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》及《[url=http://www.1sucai.cn/Special/516.htm]Python文件与目录操作技巧汇总[/url]》
希望本文所述对大家Python程序设计有所帮助。