python生成随机数方法小结
在Python中用于生成随机数的模块是random,在使用前需要import
random.random:
random.random():生成一个0-1之间的随机浮点数.例:
1 import random
2 print random.random()
3 #0.87594424128
random.uniform
random.uniform(a, b):生成[a,b]之间的浮点数.例:
1 import random
2 print random.uniform(0,10)
3 #5.27462570463
random.ranint
random.randint(a, b):生成[a,b]之间的整数.例:
1 import random
2 print random.randint(0,10)
3 # 8
random.randrange
random.randrange(a, b, step):在指定的集合[a,b)中,以step为基数随机取一个数.如random.randrange(0, 20, 2),相当于从[0,2,4,6,…,18]中随机取一个.例:
1 import random
2 print random.randrange(0,20, 2)
3 # 14
random.choice
random.choice(sequence):从特定序列中随机取一个元素,这里的序列可以是字符串,列表,元组等,例:
1 importrandom
2 string = 'niceto meet you'
3 tup = ('nice','to', 'meet', 'you')
4 lst = ['nice','to', 'meet', 'you']
5 dic = {'a': 1,'b': 2, 'c': 3}
6 printrandom.choice(string)
7 print random.choice(tup)
8 printrandom.choice(lst)
9 ——————
10 c
11 meet
12 nice
13 ——————
random.shuffle
random.shuffle(lst):将列表中的元素打乱,洗牌.例:
1 importrandom
2 lst = ['nice','to', 'meet', 'you']
3 random.shuffle(lst)
4 printlst
5 # ['you', 'nice','to', 'meet']
random.sample
random.sample(sequence,k):从指定序列在随机抽取定长序列,原始序列不变,例:
1 importrandom
2 string = 'niceto meet you'
3 tup = ('nice','to', 'meet', 'you')
4 lst = ['nice','to', 'meet', 'you']
5 dic = {'a': 1,'b': 2, 'c': 3}
6 printrandom.sample(string, 2)
7 printrandom.sample(tup, 2)
8 printrandom.sample(lst, 2)
9 ——————
10 ['m', 'i']
11 ['you','nice']
12 ['nice','to']
13 ——————