etc./StackOverFlow

목록에서 항목을 무작위로 선택하려면 어떻게 합니까?

청렴결백한 만능 재주꾼 2021. 12. 20. 10:11
반응형

질문자 :Ray


다음 목록이 있다고 가정합니다.

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

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

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

Pēteris Caune

목록에서 하나 이상의 항목을 무작위로 선택하거나 세트에서 항목을 선택하려면 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]

그러나 목록에서 단일 항목만 가져오는 경우 선택이 덜 복잡합니다. sample을 사용하면 random.choice(some_list) 대신 random.sample(some_list, 1)[0] 구문이 사용되기 때문입니다.

불행히도 선택은 시퀀스(예: 목록 또는 튜플)의 단일 출력에만 작동합니다. random.choice(tuple(some_set)) 는 세트에서 단일 항목을 가져오는 옵션일 수 있습니다.

편집: 비밀 사용

많은 사람들이 지적했듯이 더 안전한 의사 난수 샘플이 필요한 경우 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 One-Liner

여러 항목을 선택하기 위해 더 파이썬적인 단일 라이너를 원하면 unpacking을 사용할 수 있습니다.

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

Paul

인덱스도 필요한 경우 random.randrange

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

Juampi

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

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

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

임의의 인덱스를 인쇄하려면:

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

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


Chris_Rands

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

목록이 비어 있을 때까지 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([])

kiriloff

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)

Fardin Abdi

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

C8H10N4O2

색인이 필요한 경우 다음을 사용하십시오.

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

random.choice 는 동일합니다 :)


Janek Olszak

목록에서 항목을 무작위로 선택하는 방법은 무엇입니까?

다음 목록이 있다고 가정합니다.

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

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

진정한 random에 가깝다 면 표준 라이브러리(Python 3.6의 새로운 기능)에서 secrets.choice 를 제안합니다.

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

위의 내용은 이전 Python 2에서 사용할 수 choice 방법과 함께 random SystemRandom 개체를 사용하는 이전 권장 사항과 동일합니다.

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

네, "seed" 인수를 전달할 수 있지만 SystemRandom 객체는 단순히 무시한다는 것을 알 수 있습니다 .

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

Aaron Hall

다음은 임의의 인덱스를 정의하는 변수가 있는 코드입니다.

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

(파이썬 2.7)


Liam

무작위 아이템 선택:

 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의 복제


Solomon Vimal

다음 코드는 동일한 항목을 생산해야 하는지 여부를 보여줍니다. 추출할 샘플 수를 지정할 수도 있습니다.
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']

Memin

다음과 같이 할 수 있습니다.

 from random import randint foo = ["a", "b", "c", "d", "e"] print(foo[randint(0,4)])

Evan Schwartzentruber

이것은 이미 답변일 수 있지만 random.shuffle 사용할 수 있습니다. 예시:

 import random foo = ['a', 'b', 'c', 'd', 'e'] random.shuffle(foo)

Jax

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)

Abdul Majeed

출처 : http:www.stackoverflow.com/questions/306400/how-can-i-randomly-select-an-item-from-a-list

반응형