python生成随机数方法小结

在python中用于生成随机数的模块是random,在使用前需要import

random.random:

random.random():生成一个0-1之间的随机浮点数.例:

import random
print random.random()
# 0.87594424128

random.uniform

random.uniform(a, b):生成[a,b]之间的浮点数.例:
import random
print random.uniform(0, 10)
# 5.27462570463

random.ranint

random.randint(a, b):生成[a,b]之间的整数.例:
import random
print random.randint(0, 10)
# 8

random.randrange

random.randrange(a, b, step):在指定的集合[a,b)中,以step为基数随机取一个数.如random.randrange(0, 20, 2),相当于从[0,2,4,6,...,18]中随机取一个.例:
import random
print random.randrange(0, 20, 2)
# 14

random.choice

random.choice(sequence):从特定序列中随机取一个元素,这里的序列可以是字符串,列表,元组等,例:
import random
string = 'nice to meet you'
tup = ('nice', 'to', 'meet', 'you')
lst = ['nice', 'to', 'meet', 'you']
dic = {'a': 1, 'b': 2, 'c': 3}
print random.choice(string)
print random.choice(tup)
print random.choice(lst)
'''
c
meet
nice
'''

random.shuffle

random.shuffle(lst):将列表中的元素打乱,洗牌.例:
import random
lst = ['nice', 'to', 'meet', 'you']
random.shuffle(lst)
print lst
# ['you', 'nice', 'to', 'meet']

random.sample

random.sample(sequence,k):从指定序列在随机抽取定长序列,原始序列不变,例:
import random
string = 'nice to meet you'
tup = ('nice', 'to', 'meet', 'you')
lst = ['nice', 'to', 'meet', 'you']
dic = {'a': 1, 'b': 2, 'c': 3}
print random.sample(string, 2)
print random.sample(tup, 2)
print random.sample(lst, 2)
'''
['m', 'i']
['you', 'nice']
['nice', 'to']
'''

你可能感兴趣的:(python)