티스토리 뷰
반응형
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How can I randomly select an item from a list?
리스트에서 아이템을 무작위로 선택하려면 어떻게 해야 합니까?
문제 내용
How do I retrieve an item at random from the following list?
다음 리스트에서 임의로 항목을 검색하려면 어떻게 해야 합니까?
foo = ['a', 'b', 'c', 'd', 'e']
높은 점수를 받은 Solution
Use random.choice()
:
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()
:
암호화된 보안 임의 선택(예: 단어 목록에서 암호 생성)의 경우 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:
secrets 은 Python 3.6 에서 새로운 것이다. 이전 버전의 Python에서는 random.SystemRandom 을 사용할 수 있습니다:
import random
secure_random = random.SystemRandom()
print(secure_random.choice(foo))
가장 최근 달린 Solution
I usually use the random module for working with lists and randomization
나는 보통 random 모듈을 리스트와 랜덤 작업에 사용합니다.
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
출처 : https://stackoverflow.com/questions/306400/how-can-i-randomly-select-an-item-from-a-list
반응형
'개발 > 파이썬' 카테고리의 다른 글
파이썬에서 리스트 길이 구하기 (0) | 2022.12.08 |
---|---|
로컬 폴더의 모든 파일 삭제하기 (0) | 2022.12.08 |
Pandas에서 SettingWithCopyWarning을 처리하는 방법 (0) | 2022.12.07 |
기존 Pandas 데이터 프레임에 새 열을 추가하기 (0) | 2022.12.07 |
빈 Pandas 데이터프레임 만든 후 한 행씩 추가하기 (0) | 2022.12.07 |
댓글
공지사항
최근에 올라온 글