Simple use of python's random module

Simple use of python's random module

random.random(): Get a floating point number in the range of [0.0,1.0)
random.randint(a,b) Get an integer in the range of [a,b]
ramdom.uniform(a,b) Get (a,b) Floating point numbers in the range
random.shuffle(x): Shuffle the elements in the data specified by the parameter, the parameter must be a variable data type
random.sample(x,k) randomly extract k data from x to form A list back

Examples are as follows:

import  random
# 获取[0.0,1.0)范围内的浮点数
print(random.random())  #比如0.8671173513600043

# 获取[a,b]范围内的一个整数
print(random.randint(3,4)) #比如3

# 获取[a,b)范围内的浮点数
print(random.uniform(3,5)) #比如3.1686045807828984

# 把参数指定的数据中的元素打乱,参数必须是一个可变的数据类型
lst = list(range(10))
random.shuffle(lst)  #注意这里如果直接print(random.shuffle(lst)) 会输出None
print(lst)  #比如[3, 8, 1, 9, 5, 2, 4, 6, 7, 0]

t =(1,2,3,4,5,6,7,8)
# random.shuffle(t)
# print(t) #这样会报错
# 通过sample变相实现打乱元组
print(random.sample(t,len(t)))

If you think this article is useful to you, please give the author a little support~ Your encouragement is a great motivation for me to move forward!

Guess you like

Origin blog.csdn.net/m0_50481455/article/details/111273382