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

问题:如何从列表中随机选择一个项目?

假设我有以下列表:

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

从此列表中随机检索项目的最简单方法是什么?

Assume I have the following list:

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

What is the simplest way to retrieve an item at random from this list?


回答 0

采用 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))

Use random.choice()

import random

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

For cryptographically secure random choices (e.g. for generating a passphrase from a wordlist) use secrets.choice()

import secrets

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

secrets is new in Python 3.6, on older versions of Python you can use the random.SystemRandom class:

import random

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

回答 1

如果您想从列表中随机选择一个以上的项目,或者从一组中选择一个项目,则建议random.sample改用。

import random
group_of_items = {1, 2, 3, 4}               # 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] 

如果您只是从列表中拉出一个项目,那么选择就不会那么笨拙,因为使用sample的语法将random.sample(some_list, 1)[0]random.choice(some_list)

但是不幸的是,选择仅适用于序列(例如列表或元组)中的单个输出。虽然random.choice(tuple(some_set))可能是从集合中获取单个项目的选项。

编辑:使用秘密

正如许多人指出的那样,如果需要更安全的伪随机样本,则应使用secrets模块:

import secrets                              # imports secure module.
secure_random = secrets.SystemRandom()      # creates a secure random object.
group_of_items = {1, 2, 3, 4}               # 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一线

如果您希望使用更具Python风格的单行代码来选择多个项目,则可以使用拆包。

import random
first_random_item, second_random_item = random.sample(group_of_items, 2)

If you want to randomly select more than one item from a list, or select an item from a set, I’d recommend using random.sample instead.

import random
group_of_items = {1, 2, 3, 4}               # 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] 

If you’re only pulling a single item from a list though, choice is less clunky, as using sample would have the syntax random.sample(some_list, 1)[0] instead of random.choice(some_list).

Unfortunately though, choice only works for a single output from sequences (such as lists or tuples). Though random.choice(tuple(some_set)) may be an option for getting a single item from a set.

EDIT: Using Secrets

As many have pointed out, if you require more secure pseudorandom samples, you should use the secrets module:

import secrets                              # imports secure module.
secure_random = secrets.SystemRandom()      # creates a secure random object.
group_of_items = {1, 2, 3, 4}               # 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]

EDIT: Pythonic One-Liner

If you want a more pythonic one-liner for selecting multiple items, you can use unpacking.

import random
first_random_item, second_random_item = random.sample(group_of_items, 2)

回答 2

如果您还需要索引,请使用 random.randrange

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

If you also need the index, use random.randrange

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

回答 3

从Python 3.6开始,您可以使用该secrets模块,该random模块比加密或安全用途的模块更好。

要从列表中打印随机元素:

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

要打印随机索引:

print(secrets.randbelow(len(foo)))

有关详细信息,请参阅PEP 506

As of Python 3.6 you can use the secrets module, which is preferable to the random module for cryptography or security uses.

To print a random element from a list:

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

To print a random index:

print(secrets.randbelow(len(foo)))

For details, see PEP 506.


回答 4

我提出了一个脚本,用于从列表中删除随机拾取的项目,直到它为空:

维持set并删除随机拾取的元素(带有choice),直到列表为空。

s=set(range(1,6))
import random

while len(s)>0:
  s.remove(random.choice(list(s)))
  print(s)

三个运行给出三个不同的答案:

>>> 
set([1, 3, 4, 5])
set([3, 4, 5])
set([3, 4])
set([4])
set([])
>>> 
set([1, 2, 3, 5])
set([2, 3, 5])
set([2, 3])
set([2])
set([])

>>> 
set([1, 2, 3, 5])
set([1, 2, 3])
set([1, 2])
set([1])
set([])

I propose a script for removing randomly picked up items off a list until it is empty:

Maintain a set and remove randomly picked up element (with choice) until list is empty.

s=set(range(1,6))
import random

while len(s)>0:
  s.remove(random.choice(list(s)))
  print(s)

Three runs give three different answers:

>>> 
set([1, 3, 4, 5])
set([3, 4, 5])
set([3, 4])
set([4])
set([])
>>> 
set([1, 2, 3, 5])
set([2, 3, 5])
set([2, 3])
set([2])
set([])

>>> 
set([1, 2, 3, 5])
set([1, 2, 3])
set([1, 2])
set([1])
set([])

回答 5

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

在python 2:

random_items = random.sample(population=foo, k=number_of_samples)

在python 3:

random_items = random.choices(population=foo, k=number_of_samples)
foo = ['a', 'b', 'c', 'd', 'e']
number_of_samples = 1

In python 2:

random_items = random.sample(population=foo, k=number_of_samples)

In python 3:

random_items = random.choices(population=foo, k=number_of_samples)

回答 6

numpy 解: numpy.random.choice

对于这个问题,它的作用与接受的答案(import random; random.choice())相同,但是我添加了它,因为程序员可能已经导入numpy了(像我一样),并且这两种方法之间可能存在一些差异,这可能与您的实际用例有关。

import numpy as np    
np.random.choice(foo) # randomly selects a single item

为了重现性,您可以执行以下操作:

np.random.seed(123)
np.random.choice(foo) # first call will always return 'c'

对于以形式返回的一个或多个项目的样本array,请传递size参数:

np.random.choice(foo, 5)          # sample with replacement (default)
np.random.choice(foo, 5, False)   # sample without replacement

numpy solution: numpy.random.choice

For this question, it works the same as the accepted answer (import random; random.choice()), but I added it because the programmer may have imported numpy already (like me) & also there are some differences between the two methods that may concern your actual use case.

import numpy as np    
np.random.choice(foo) # randomly selects a single item

For reproducibility, you can do:

np.random.seed(123)
np.random.choice(foo) # first call will always return 'c'

For samples of one or more items, returned as an array, pass the size argument:

np.random.choice(foo, 5)          # sample with replacement (default)
np.random.choice(foo, 5, False)   # sample without replacement

回答 7

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

假设我有以下列表:

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

从此列表中随机检索项目的最简单方法是什么?

如果您想接近真正的随机性,那么我建议secrets.choice从标准库(Python 3.6中的新增功能)中进行建议:

>>> from secrets import choice         # Python 3 only
>>> choice(list('abcde'))
'c'

上面的内容等同于我以前的建议,即使用模块中的SystemRandom对象randomchoice方法-早于Python 2:

>>> import random                      # Python 2 compatible
>>> sr = random.SystemRandom()
>>> foo = list('abcde')
>>> foo
['a', 'b', 'c', 'd', 'e']

现在:

>>> sr.choice(foo)
'd'
>>> sr.choice(foo)
'e'
>>> sr.choice(foo)
'a'
>>> sr.choice(foo)
'b'
>>> sr.choice(foo)
'a'
>>> sr.choice(foo)
'c'
>>> sr.choice(foo)
'c'

如果需要确定性伪随机选择,请使用choice函数(实际上是Random对象上的绑定方法):

>>> random.choice
<bound method Random.choice of <random.Random object at 0x800c1034>>

看来是随机的,但实际上不是,我们可以看看是否反复播种:

>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')

一条评论:

这与random.choice是否真正随机无关。如果修复种子,您将获得可重复的结果-这就是种子的设计目的。您也可以将种子传递给SystemRandom。sr = random.SystemRandom(42)

好吧,是的,您可以给它传递一个“种子”参数,但是您会看到该SystemRandom对象只是忽略了它

def seed(self, *args, **kwds):
    "Stub method.  Not used for a system random number generator."
    return None

How to randomly select an item from a list?

Assume I have the following list:

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

What is the simplest way to retrieve an item at random from this list?

If you want close to truly random, then I suggest secrets.choice from the standard library (New in Python 3.6.):

>>> from secrets import choice         # Python 3 only
>>> choice(list('abcde'))
'c'

The above is equivalent to my former recommendation, using a SystemRandom object from the random module with the choice method – available earlier in Python 2:

>>> import random                      # Python 2 compatible
>>> sr = random.SystemRandom()
>>> foo = list('abcde')
>>> foo
['a', 'b', 'c', 'd', 'e']

And now:

>>> sr.choice(foo)
'd'
>>> sr.choice(foo)
'e'
>>> sr.choice(foo)
'a'
>>> sr.choice(foo)
'b'
>>> sr.choice(foo)
'a'
>>> sr.choice(foo)
'c'
>>> sr.choice(foo)
'c'

If you want a deterministic pseudorandom selection, use the choice function (which is actually a bound method on a Random object):

>>> random.choice
<bound method Random.choice of <random.Random object at 0x800c1034>>

It seems random, but it’s actually not, which we can see if we reseed it repeatedly:

>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')
>>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
('d', 'a', 'b')

A comment:

This is not about whether random.choice is truly random or not. If you fix the seed, you will get the reproducible results — and that’s what seed is designed for. You can pass a seed to SystemRandom, too. sr = random.SystemRandom(42)

Well, yes you can pass it a “seed” argument, but you’ll see that the SystemRandom object simply ignores it:

def seed(self, *args, **kwds):
    "Stub method.  Not used for a system random number generator."
    return None

回答 8

如果您需要索引,请使用:

import random
foo = ['a', 'b', 'c', 'd', 'e']
print int(random.random() * len(foo))
print foo[int(random.random() * len(foo))]

random.choice做同样的事情:)

if you need the index just use:

import random
foo = ['a', 'b', 'c', 'd', 'e']
print int(random.random() * len(foo))
print foo[int(random.random() * len(foo))]

random.choice does the same:)


回答 9

这是带有定义随机索引的变量的代码:

import random

foo = ['a', 'b', 'c', 'd', 'e']
randomindex = random.randint(0,len(foo)-1) 
print (foo[randomindex])
## print (randomindex)

这是没有变量的代码:

import random

foo = ['a', 'b', 'c', 'd', 'e']
print (foo[random.randint(0,len(foo)-1)])

这是用最短和最聪明的方法实现的代码:

import random

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

(python 2.7)

This is the code with a variable that defines the random index:

import random

foo = ['a', 'b', 'c', 'd', 'e']
randomindex = random.randint(0,len(foo)-1) 
print (foo[randomindex])
## print (randomindex)

This is the code without the variable:

import random

foo = ['a', 'b', 'c', 'd', 'e']
print (foo[random.randint(0,len(foo)-1)])

And this is the code in the shortest and smartest way to do it:

import random

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

(python 2.7)


回答 10

以下代码演示了是否需要生产相同的物品。您还可以指定要提取的样本数量。
sample方法返回一个新列表,其中包含总体中的元素,而保留原始总体不变。结果列表按选择顺序排列,因此所有子切片也将是有效的随机样本。

import random as random
random.seed(0)  # don't use seed function, if you want different results in each run
print(random.sample(foo,3))  # 3 is the number of sample you want to retrieve

Output:['d', 'e', 'a']

The following code demonstrates if you need to produce the same items. You can also specify how many samples you want to extract.
The sample method returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples.

import random as random
random.seed(0)  # don't use seed function, if you want different results in each run
print(random.sample(foo,3))  # 3 is the number of sample you want to retrieve

Output:['d', 'e', 'a']

回答 11

随机项目选择:

import random

my_list = [1, 2, 3, 4, 5]
num_selections = 2

new_list = random.sample(my_list, num_selections)

要保留列表的顺序,您可以执行以下操作:

randIndex = random.sample(range(len(my_list)), n_selections)
randIndex.sort()
new_list = [my_list[i] for i in randIndex]

重复的https://stackoverflow.com/a/49682832/4383027

Random item selection:

import random

my_list = [1, 2, 3, 4, 5]
num_selections = 2

new_list = random.sample(my_list, num_selections)

To preserve the order of the list, you could do:

randIndex = random.sample(range(len(my_list)), n_selections)
randIndex.sort()
new_list = [my_list[i] for i in randIndex]

Duplicate of https://stackoverflow.com/a/49682832/4383027


回答 12

我们也可以使用randint做到这一点。

from random import randint
l= ['a','b','c']

def get_rand_element(l):
    if l:
        return l[randint(0,len(l)-1)]
    else:
        return None

get_rand_element(l)

We can also do this using randint.

from random import randint
l= ['a','b','c']

def get_rand_element(l):
    if l:
        return l[randint(0,len(l)-1)]
    else:
        return None

get_rand_element(l)

回答 13

您可以:

from random import randint

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

print(foo[randint(0,4)])

You could just:

from random import randint

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

print(foo[randint(0,4)])