python built-in module random

Introduction to the random module

Random is a built-in module in python, which is used to generate pseudo-random numbers, not really random numbers. The random module is often used in daily life, so I will briefly introduce it today.

Common methods of random module

random.random() Randomly generate a floating point number in the range of [0,1) and return this floating point number
random.randint(a,b) Given a range, randomly generate an integer [a,b] and return this integer
random.randrange(a,b,s) Given a range, randomly generate an integer of [a,b) and return this integer, s represents the step size
random.shuffle(x) Shuffle the order of the list x, the return value is None
random.choice(seq) Return a random element from the non-empty sequence (list, char) seq. Raises IndexError if seq is null.
ranomd.seed() Set the seed for the random number generator
random.sample(data,num) Randomly select multiple elements from a sequence

Method demonstration

import random

# 随机生成从0到1之间的浮点数
f_num = random.random()
print(f_num)

# 随机生成从1到10之间的整数,包括1和10
i_num = random.randint(1, 10)
print(i_num)

# 随机生成1 3 5 7 9 当中的一个数
i_nums = random.randrange(1, 10, 2)
print(i_nums)

# 将list_num打乱 返回值为None
list_num = [1, 2, 3, 4, 5]
random.shuffle(list_num)
print(list_num)

# 从列表中随机选取一个值并返回此值
random_num = random.choice([1, 2, 4, 5])
print(random_num)

# 从序列中抽取多个元素
data = [1, 2, 3, 4]
print(random.sample(data, 2))

seed() random number seed

What is the random number seed? It is equivalent to giving an initial value that needs to generate random numbers, and then generating random numbers in order. We can use seed() to change the seed of the generator. If not set, the system default seed will be used to generate random numbers. If the same seed is set, and the order corresponds one to one, the generated random numbers are the same. as follows

import random
# 生成的值对照就会发现是相同的

random.seed(10)
print(random.random())
print(random.random())

# 结果是相同的
random.seed(10)
print(random.random())
print(random.random())

Finally, if there is an error in the article, please correct me, thank you! ! !

Guess you like

Origin blog.csdn.net/qq_65898266/article/details/124936395