# python 3.6 随机数

xiaoxiao2021-03-01  13

### 随机数模块

Python中，有一个叫做random的内置模块，可以很方便的为我们生成各式的随机数据

#### 随机整数

random.randrange( stop )

1 2 >>> random.randrange(20) 7 random.randrange( start, stop, step )

1 2 3 4 5 6 7 8 >>> random.randrange(0,10,3) 3 >>> random.randrange(0,10,3) 6 >>> random.randrange(0,10,3) 6 >>> random.randrange(0,10,3) 9 random.randint(start, stop)

1 2 3 4 5 6 >>> random.randint(10,20) 19 >>> random.randint(10,20) 19 >>> random.randint(10,20) 10 random.getrandbits(num)

1 2 3 4 5 6 >>> random.getrandbits(3)#(2**3) 5 >>> random.getrandbits(3) 2 >>> random.getrandbits(3) 1

#### 随机浮点数

random.random()

1 2 3 4 >>> random.random() 0.018594388691108188 >>> random.random() 0.7626285486964196 random.uniform(start, stop)

1 2 3 4 5 6 >>> random.uniform(1,3) 1.5281489461709883 >>> random.uniform(1,3) 1.0881355542393485 >>> random.uniform(1,3) 1.4888568616457178

#### 随机序列

random.choice(seq)

1 2 3 4 >>> random.choice([1,2,3,4,5]) 3 >>> random.choice([1,2,3,4,5]) 2 random.shuffle(seq)

1 2 3 4 >>> mylist = [1,2,3,4,5] >>> random.shuffle(mylist) >>> mylist [5, 4, 1, 3, 2] random.sample(seq,num)

1 2 3 4 5 6 >>> random.sample(mylist,3) [3, 4, 1] >>> random.sample(mylist,3) [5, 4, 1] >>> random.sample(mylist,3) [5, 2, 4]