本文摘自php中文网,作者不言,侵删。
这篇文章主要介绍了Python生成随机数的方法,有需要的朋友可以参考一下如果你对在Python生成随机数与random模块中最常用的几个函数的关系与不懂之处,下面的文章就是对Python生成随机数与random模块中最常用的几个函数的关系,希望你会有所收获,以下就是这篇文章的介绍。
random.random()用于生成
用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。如果a > b,则生成随机数
1 |
|
1 2 3 4 5 6 |
|
用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,Python生成随机数
1 2 3 |
|
下限必须小于上限。
random.randrange
从指定范围内,按指定基数递增的集合中 ,这篇文章就是对python生成随机数的应用程序的部分介绍。
随机整数:
>>> import random
>>> random.randint(0,99)
21
随机选取0到100间的偶数:
>>> import random
>>> random.randrange(0, 101, 2)
42
随机浮点数:
>>> import random
>>> random.random()
0.85415370477785668
>>> random.uniform(1, 10)
5.4221167969800881
随机字符:
>>> import random
>>> random.choice('abcdefg%^*f')
'd'
多个字符中选取特定数量的字符:
>>> import random
random.sample('abcdefghij',3)
['a', 'd', 'b']
多个字符中选取特定数量的字符组成新字符串:
>>> import random
>>> import string
>>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).r
eplace(" ","")
'fih'
随机选取字符串:
>>> import random
>>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )
'lemon'
洗牌:
>>> import random
>>> items = [1, 2, 3, 4, 5, 6]
>>> random.shuffle(items)
>>> items
[3, 2, 5, 6, 4, 1]
PS:最后再为大家提供两款相关在线工具供大家参考使用:
在线随机数字/字符串生成工具:
http://tools.jb51.net/aideddesign/suijishu
高强度随机字符密码生成器:
相关推荐:
php 生成随机数的三种方法代码示例
php?生成随机数解决方案
以上就是Python生成随机数的方法_python的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python数据结构:一个被低估的namedtuple(一)
Python中列表中的pop方法与remove方法有什么区别
更多相关阅读请进入《Python》频道 >>
Python编程 从入门到实践 第2版
python入门书籍,非常畅销,超高好评,python官方公认好书。