Home  >  Article  >  Backend Development  >  Detailed explanation of the function of randomly selecting elements in Python

Detailed explanation of the function of randomly selecting elements in Python

巴扎黑
巴扎黑Original
2017-09-16 10:09:071798browse

This article mainly introduces the function of randomly selecting elements in Python in detail. It has certain reference value. Interested friends can refer to it.

If you want to randomly select elements from the sequence, we You can use the random.choice() method of the random module:

Detailed explanation of the function of randomly selecting elements in Python

If you want to take out N elements and place the selected elements for further inspection, you can use random .sample() method:

Detailed explanation of the function of randomly selecting elements in Python

If we just want to disrupt the order of the sequence (shuffle), we can use random.shuffle():

Detailed explanation of the function of randomly selecting elements in Python

To generate random numbers, you can use the random.randint() method:

Detailed explanation of the function of randomly selecting elements in Python

If you want to generate a uniformly distributed floating number between 0-1 For point values, you can use the random.random() method:

Detailed explanation of the function of randomly selecting elements in Python

#If you want to get the integer represented by N random bits, you can use the random.getrandbits() method:

Detailed explanation of the function of randomly selecting elements in Python

Please note:

The random module uses the Mersenne Twister algorithm (Mersenne Twister, also known as the Mersenne Twister algorithm) to calculate random Number, this is a deterministic algorithm, but you can modify the seed value through the random.seed() function


random.seed()
#基于系统时间或者是os.urandom()函数
random.seed(6666)
#基于给定整数
random.seed(b'bytes') 
#基于给定的字节数据

random module In addition to the application of random numbers It can also be used to calculate uniform distribution, Gaussian distribution and other probability distributions


random.uniform
#计算均匀分布
random.gauss()
#计算高斯分布(正态分布)

Note: Please do not use the random module in encryption-related programs. If there is such For application requirements, please consider using the functions in the ssl module instead, for example:


ssl.RAND_bytes()
#用来生成加密安全的随机字节序列

Detailed explanation of the function of randomly selecting elements in Python

The above is the detailed content of Detailed explanation of the function of randomly selecting elements in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn