Python标准模块学习主要以在代码的形式来记录,每行代码都实际运行过,如有疑问或更好的实现方法,欢迎留言,非常感谢,大家共同学习。
random 模块是Python自带的模块,除了生成最简单的随机数以外,还有很多功能。让我们看下常用的功能吧:
在使用该模块之前,一定要先导入模块
import random
1. random() 生成0-1的随机数 [0,1)范围
x = random.random()
y = random.random()
print('0-1随机浮点数:',x, y)
:0-1随机浮点数: 0.39082481046855455 0.5771816227311238
2. randint(num1,num2) 生成随机整数 范围[num1,num2],注意:传入参数必须是整数,num1一定要比num2小
x = random.randint(1,10)
y = random.randint(1,20)
print('随机整数:',x, y)
:随机整数: 1 5
3. choice(sequence_arg) 随机取样,参数必须为序列,因为是按照索引去选择的
str_one = 'hello world!'
lst = list(range(1000))
x = random.choice(str_one)
y = random.choice(lst)
print('随机取样:',x, y)
:随机取样: w 846
4. sample(sequence_arg) 随机取指定数量的元素 参数必须为序列,因为是按照索引去选择的
print(random.sample(5,1)) #报错TypeError: Population must be a sequence or set. For dicts, use list(d)
x = random.sample(str_one,2)
y = random.sample(lst,5)
print('随机取指定数量的元素:',x, y)
:随机取指定数量的元素: ['d', 'w'] [836, 155, 628, 463, 258]
5. 打乱排序
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
random.shuffle(items)
print('随机数打乱排序后的结果:',items)
:随机数打乱排序后的结果: [3, 7, 6, 4, 5, 8, 2, 1, 9, 0]
6. randrange 随机选取[num1,num2)范围内的数字,步长为n
result = random.randrange(0, 11, 2) #随机选取0到10间的偶数 10
print('随机选取0到10间的偶数:', result)
:随机选取0到10间的偶数: 4