secrets 모듈을 사용해 리스트에서 무작위 item 추출하는 방법 (Extracting a random member from a list)
리스트에서 무작위로 배열안의 멤버를 추출하는 법을 소개한다.
(I introduce a simple way to extract one random member from a list. with python)
물론 random모듈로,
(Of course, you could do the same thing with random module.)
import random
alist= [1,3,4,5,3,2,1]
n = random.randint(0, len(alist)-1))
print(alist[n])
으로 해도 큰 문제는 없다마는 다음 세줄의 코드를 두줄로 줄일 수 있다.
(There is no problem doing it with random module as you see. But it requires 3 lines besides the import statement.)
python3.6.3에는 secrets이라는 모듈이 새로 생겼다. 훨씬 좋은 난수 발생기라고 한다.
(In python 3.6.3, the latest version as of this writing, there is a new module called secrets. According to the documentation, it produces much better randomness, which I still do not understand exactly.)
The
secrets
module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.
import secrets
alist= [1,3,4,5,3,2,1]
print(secrets.choice(alist))
이렇게 하면 좀 더 깔끔하고 쉬운 코드로 무작위 추출을 할 수 있다.
(You can extract one random member from a list only with 2 lines.) Good.
'Regular Python' 카테고리의 다른 글
파이썬 format을 이용해 초간단하게 1000의 단위마다 콤마 붙이기 (Putting comma every 3 digit in python) (0) | 2017.12.06 |
---|---|
ast module for converting a List-type-string into a real python list (0) | 2017.05.07 |