Python基础之random模块

1. 随机小数

random() :随机生成一个介于0.0到1.0之间的任意浮点数,属于左闭右开区间。没有参数,返回值为一个浮点数。

uniform(a, b):生成参数a到b之间的浮点数的函数,如果a > b,则生成b到a之间的浮点数,属于左闭右开区间,返回值为一个浮点数。

import random

print(random.random())
print(random.uniform(1, 10))

结果:

0.9306264831530425
1.1743305025936537

Process finished with exit code 0

2. 随机整数

randint(start, stop):产生整数随机数。参数start代表最小值,参数stop代表最大值,属于闭区间,返回值为一个整数。

random.randrange(start,stop,step):生成整数随机数。参数start代表最小值,参数stop代表最大值,属于左开右闭区间,返回值为一个整数。

import random

print(random.randint(1, 10))
print(random.randrange(1, 10))

结果:

10
6

Process finished with exit code 0

3. 随机返回

choice(seq):随机返回一个值。参数seq为一个非空集合,在集合中速随机选择一个数输出,元素类型没有限制。

sample(population, k):从集合中随机抽取K个元素形成新的序列,不会改变原有的序列。参数population表示一个参数序列,k表示取值个数,返回值为一个序列。

import random

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]

print(random.choice(lst))
print(random.sample(lst, 2))

结果:

8
[1, 8]

Process finished with exit code 0

4. 打乱顺序

shuffle(seq, random=None):对传入的集合进行乱序操作。只能针对可变序列,如字符串、列表,对于元组等不可变序列会报错。参数random用来选择乱序操作的方式,如:random=random。返回值None。

import random

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
random.shuffle(lst, random=None)
print(lst)

结果:

[3, 1, 5, 9, 7, 8, 2, 4, 6]

Process finished with exit code 0


面试题

1. 下面是生成一个包含大写字母A-Z和数字0-9的随机4位验证码的程序

import random

code_list = []
for i in range(10):
    code_list.append(str(i))

for i in range(65, 91):
    code_list.append(chr(i))

for i in range(97, 123):
    code_list.append(chr(i))

my_slice = random.sample(code_list, 6)
verification_code = ''.join(my_slice)
print(verification_code)

结果:

lte3IB

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/qq_33567641/article/details/81513813