如何从以下列表中随机检索项目?

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

当前回答

我建议使用一个脚本来删除列表中随机选取的项目,直到列表为空:

维护一个集合并删除随机选取的元素(有选择),直到列表为空。

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([])

其他回答

我建议使用一个脚本来删除列表中随机选取的项目,直到列表为空:

维护一个集合并删除随机选取的元素(有选择),直到列表为空。

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([])

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

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

推荐的numpy方式是使用显式RNG:

from numpy.random import default_rng

rng = default_rng()
rng.choice(foo)

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

Python 3.6中的新秘密。在旧版本的Python上,可以使用random.SystemRandom类:

import random

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

如果需要索引,只需使用:

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

random.choice也会这样做:)