如何从列表中随机选择一个项?

2369 投票
18 回答
2209137 浏览
提问于 2025-04-11 18:56

我该如何从下面的列表中随机获取一个项目呢?

foo = ['a', 'b', 'c', 'd', 'e']

18 个回答

191

如果你还需要索引的话,可以使用 random.randrange 这个函数。

from random import randrange
random_index = randrange(len(foo))
print(foo[random_index])
287

如果你想从一个列表中随机选择多个项目,或者从一个集合中选择一个项目,我建议你使用 random.sample

import random
group_of_items = {'a', 'b', 'c', 'd', 'e'}  # a sequence or set will work here.
num_to_select = 2                           # set the number to select here.
list_of_random_items = random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1] 

不过,如果你只是想从列表中抽取一个项目,使用 random.choice(some_list) 会更简单,因为如果用 random.sample(some_list, 1)[0] 就显得有点繁琐了。

但是,random.choice 只能从序列(比如列表或元组)中选出一个项目。如果你想从集合中选一个,可以用 random.choice(tuple(some_set))

编辑:使用 Secrets 模块

很多人提到,如果你需要更安全的伪随机样本,应该使用 secrets 模块:

import secrets                              # imports secure module.
secure_random = secrets.SystemRandom()      # creates a secure random object.
group_of_items = {'a', 'b', 'c', 'd', 'e'}  # a sequence or set will work here.
num_to_select = 2                           # set the number to select here.
list_of_random_items = secure_random.sample(group_of_items, num_to_select)
first_random_item = list_of_random_items[0]
second_random_item = list_of_random_items[1]

编辑:Pythonic 一行代码

如果你想用更简洁的方式选择多个项目,可以使用解包的方式。

import random
first_random_item, second_random_item = random.sample({'a', 'b', 'c', 'd', 'e'}, 2)
3430

使用 random.choice() 方法来随机选择一个元素:

import random

foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))

如果你需要更安全的随机选择,比如从一个单词列表中生成一个密码短语,可以使用 secrets.choice() 方法:

import secrets

foo = ['battery', 'correct', 'horse', 'staple']
print(secrets.choice(foo))

secrets 是在 Python 3.6 版本中新增的。如果你使用的是旧版本的 Python,可以用 random.SystemRandom 类来实现:

import random

secure_random = random.SystemRandom()
print(secure_random.choice(foo))

撰写回答