python之生成随机数

#random函数的各种使用方法
import random

#随机生成[0,1)的浮点数
print("random():",random.random())

#随机生成3-10之间的浮点数
print("uniform(3,10):",random.uniform(3,10))

#随机生成10-20之间的整数
print("randint(10,20):",random.randint(10,20))

#随机生成20-30之间的偶数
print("randrange(20,30,2):",random.randrange(20,30,2))

#从序列中随机选择一个元素
list_str1='abcde'
list_str2=['l','o','v','e']
print("choice(list_str1):",random.choice(list_str1))
print("choice(list_str2):",random.choice(list_str2))

#对列表中的元素随机排序
list_num1=[3,2,1,4,5]
list_num2=['7','8','6','9','5']
random.shuffle(list_num1)
random.shuffle(list_num2)
print("shuffle(list_num1)",list_num1)
print("shuffle(list_num2)",list_num2)

#从指定序列中随机获取n个片段
list_string='hunter'
print("sample(list_string,2):",random.sample(list_string,2))

#随机生成40-50之间不重复的n个数
print("sample(range(40,50),4):",random.sample(range(40,50),4))

运行结果:

random(): 0.2141639435323659
uniform(3,10): 7.297496874443817
randint(10,20): 19
randrange(20,30,2): 28
choice(list_str1): d
choice(list_str2): o
shuffle(list_num1) [1, 5, 4, 3, 2]
shuffle(list_num2) ['5', '8', '6', '9', '7']
sample(list_string,2): ['e', 'n']
sample(range(40,50),4): [49, 40, 44, 47]

猜你喜欢

转载自blog.csdn.net/beautiful77moon/article/details/86488509