Random selection implemented in python

Like elements from a plurality of random sequences, or you want to generate several random numbers.

random module has a number of functions used to generate the random number and the random selection element. For example, in order to extract a random element from a sequence can be used random.choice ():

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

In order to extract a sample of N different elements used for further operations, may be used random.sample ()

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:××× 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> random.sample(values, 2)
[6, 2]
>>> random.sample(values, 2)
[4, 3]
>>> random.sample(values, 3)
[4, 3, 1]

If you just want to upset the order of elements in the sequence, you can use random.shuffle ():

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

Generating a random integer, use random.randint ():

>>> random.randint(0,10)
2
>>> random.randint(0,10)
5

To generate uniformly distributed in the range of floating-point 0-1, using random.random ():

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:××× 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> random.random()
0.9406677561675867
>>> random.random()
0.133129581343897

To obtain the N-bit random integer bit (binary) using random.getrandbits ():

>>> random.getrandbits(200)
335837000776573622800628485064121869519521710558559406913275

The functions of the above presentation, based Random module further comprises a uniform, Gaussian and other random number generation function distribution. For example, random.uniform () uniformly distributed random number is calculated, random.gauss () is calculated normally distributed random number. For other distributions, please refer to the online documentation.
Function in the random module should not be used in the program and the related cryptography. If you do need similar functionality, you can use the ssl module in the corresponding function. For example, ssl.RAND bytes () can be used to generate a secure random sequence of bytes.

Guess you like

Origin blog.51cto.com/14246112/2447216