Python随机数用法实例详解【基于random模块】 本文实例讲述了Python随机数用法。分享给大家供大家参考,具体如下: 1. random.seed(int) 给随机数对象一个种子值,用于产生随机序列。 对于同一个种子值的输入,之后产生的随机数序列也一样。 通常是把时间秒数等变化值作为种子值,达到每次运行产生的随机系列都不一样 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() 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','2','3','5','6','7'] print item2 random.shuffle(item2) print item2 PS:这里再为大家提供两款相关在线工具供大家参考使用: 在线随机数字/字符串生成工具: http://tools.zwyuanma.com/aideddesign/suijishu 高强度密码生成器: http://tools.zwyuanma.com/password/CreateStrongPassword 更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》 希望本文所述对大家Python程序设计有所帮助。