## Notes on Python cookbook 3rd (3.11): random selection

Giant ship 2020-11-18 00:30:39
notes python cookbook 3rd rd

# Random selection

## problem

You want to randomly extract a number of elements from a sequence , Or you want to generate a few random numbers .

## solution

random Modules have a lot of functions to generate random numbers and random selection elements . such as , To randomly extract an element from a sequence , have access to random.choice() ：

``````>>> import random
>>> values = [1, 2, 3, 4, 5, 6]
>>> random.choice(values)
2
>>> random.choice(values)
3
>>> random.choice(values)
1
>>> random.choice(values)
4
>>> random.choice(values)
6
>>>
``````

In order to extract N Samples of different elements are used for further operations , have access to random.sample()：

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

If you just want to disorganize the elements in the sequence , have access to random.shuffle() ：

``````>>> random.shuffle(values)
>>> values
[2, 4, 6, 5, 3, 1]
>>> random.shuffle(values)
>>> values
[3, 5, 2, 1, 6, 4]
>>>
``````

Generate random integer , Please use random.randint()：

``````>>> random.randint(0,10)
2
>>> random.randint(0,10)
5
>>> random.randint(0,10)
0
>>> random.randint(0,10)
7
>>> random.randint(0,10)
10
>>> random.randint(0,10)
3
>>>
``````

In order to generate 0 To 1 Floating point numbers evenly distributed over a range , Use random.random() ：

``````>>> random.random()
0.9406677561675867
>>> random.random()
0.133129581343897
>>> random.random()
0.4144991136919316
>>>
``````

If you want to get N Bit random bit ( Binary system ) The integer of , Use random.getrandbits() ：

``````>>> random.getrandbits(200)
335837000776573622800628485064121869519521710558559406913275
>>>
``````

## Discuss

random Module USES Mersenne Twister Algorithm to calculate the generated random number . This is a deterministic algorithm , But you can go through random.seed() Function modify initialization seed . such as ：

``````random.seed() # Seed based on system time or os.urandom()
random.seed(12345) # Seed based on integer given
random.seed(b'bytedata') # Seed based on byte data
``````

In addition to the functions described above , random Modules also include uniform distribution based 、 The function of generating random numbers of Gauss distribution and other distribution . such as , random.uniform() Calculate the random number of uniform distribution , random.gauss() Calculate the random number of normal distribution . For other distribution, please refer to the online documentation .

stay random Functions in modules should not be used in cryptography related programs . If you really need similar features , have access to ssl The corresponding function in the module . such as , ssl.RAND bytes() Can be used to generate a secure sequence of random bytes .