Python常用随机数与随机字符串方法实例

yipeiwu_com6年前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]

random的函数还有很多,此处不一一列举,
参考资料: http://docs.python.org/lib/module-random.html

相关文章

Golang与python线程详解及简单实例

Golang与python线程详解及简单实例 在GO中,开启15个线程,每个线程把全局变量遍历增加100000次,因此预测结果是 15*100000=1500000. var sum...

python用reduce和map把字符串转为数字的方法

python中reduce和map简介 map(func,seq1[,seq2...]) :将函数func作用于给定序列的每个元素,并用一个列表来提供返回值;如果func为None,fu...

Python 匹配任意字符(包括换行符)的正则表达式写法

想使用正则表达式来获取一段文本中的任意字符,写出如下匹配规则: (.*) 结果运行之后才发现,无法获得换行之后的文本。于是查了一下手册,才发现正则表达式中,“.”(点符号)匹配的是除了换...

python中的reduce内建函数使用方法指南

官方解释: Apply function of two arguments cumulatively to the items of iterable, from left to r...

解决tensorflow测试模型时NotFoundError错误的问题

错误代码如下: NotFoundError (see above for traceback): Unsuccessful TensorSliceReader constructor...