在Python中用于生成随机数的模块是random
random.random():生成一个0-1之间的随机浮点数
>>> import random >>> random.random() 0.12313297204612084
random.uniform(a, b):生成[a,b]之间的浮点数
>>> random.uniform(1,4)
3.1979457484742237
random.randint(a, b):生成[a,b]之间的整数
>>> random.randint(1,24)
20
random.randrange(a, b, step):在指定的集合[a,b)中,以step为基数随机取一个数.如random.randrange(0, 20, 2),相当于从[0,2,4,6,...,18]中随机取一个
>>> random.randrange(0,88,2)
24
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(lst):将列表中的元素打乱,洗牌
import random lst = ['nice', 'to', 'meet', 'you'] random.shuffle(lst) print(lst) # ['you', 'nice', 'to', 'meet']
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'] '''