一、使用RANDOM库
random库是python的内置库。
1、使用random.randrange(list_length)用于返回介于0到list_index-1之间的一个随机值。
import random
random_value = random.randrange(len(list))
2、使用random.choice(list)将列表作为输入,返回列表中的一个随机元素。
import random
random_value = random.choice(list)
3、使用random.sample(list_name, number)返回列表中指定number个随机元素。
import random
random_value = random.sample(list, number)
二、使用secrets库
目录
secrets库是比random库更安全的python内置库,专门用于生成密码级的安全随机数。
1、使用secrets.randbelow(list_length)用于返回介于0到list_index-1之间的一个安全随机索引。
import secrets
random_index = secrets.randbelow(len(list))
random_value = list[random_index]
2、使用secrets.choice(list_name)将列表作为输入,返回列表中的一个安全随机元素。
3、使用secrets.SystemRandom().sample(list_name, number)返回列表中指定number个安全随机元素。
文章出处登录后可见!
已经登录?立即刷新