목록에서 항목을 무작위로 선택하는 방법은 무엇입니까? ‘c’, ‘d’, ‘e’] 이 목록에서 무작위로 항목을 검색하는

다음 목록이 있다고 가정하십시오.

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

이 목록에서 무작위로 항목을 검색하는 가장 간단한 방법은 무엇입니까?



답변

사용하다 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))

secretsPython 3.6의 새로운 기능으로, 이전 버전의 Python에서는 다음 random.SystemRandom클래스를 사용할 수 있습니다 .

import random

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

답변

목록에서 둘 이상의 항목을 임의로 선택하거나 세트에서 항목을 선택하려면 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 One-Liner

여러 항목을 선택하기 위해 더 많은 파이 토닉 원 라이너를 원한다면 포장 풀기를 사용할 수 있습니다.

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

답변

색인이 필요한 경우 random.randrange

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

답변

Python 3.6부터는 secrets모듈을 사용할 수 있으며 이는 random암호화 또는 보안 용도로 모듈 보다 선호됩니다 .

목록에서 임의의 요소를 인쇄하려면

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

무작위 색인을 인쇄하려면 다음을 수행하십시오.

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

자세한 내용은 PEP 506을 참조하십시오 .


답변

목록이 비어있을 때까지 무작위로 선택한 항목을 제거하는 스크립트를 제안합니다.

목록을 비울 때까지 a를 유지하고 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([])

답변

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

파이썬 2에서 :

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

파이썬 3에서 :

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

답변

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'

하나 이상의 items 샘플을 로 반환 array하려면 size인수를 전달하십시오 .

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