一、使用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库
目录
1、使用random.randrange(list_length)用于返回介于0到list_index-1之间的一个随机值。
2、使用random.choice(list)将列表作为输入,返回列表中的一个随机元素。
3、使用random.sample(list_name, number)返回列表中指定number个随机元素。
1、使用secrets.randbelow(list_length)用于返回介于0到list_index-1之间的一个安全随机索引。
2、使用secrets.choice(list_name)将列表作为输入,返回列表中的一个安全随机元素。
3、使用secrets.SystemRandom().sample(list_name, number)返回列表中指定number个安全随机元素。
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]
Python获取列表随机元素:random与secrets库
本文介绍了Python中使用random和secrets库来获取列表中的随机元素。random库提供了randrange()、choice()和sample()方法,而secrets库则提供更安全的randbelow()、choice()以及SystemRandom().sample()方法,适用于生成密码级安全的随机索引和元素。
217

被折叠的 条评论
为什么被折叠?



