A random element in a python list can easily extracted with a newly added module called "secrets".
Without secrets module, you may consider a code as show below.
import random
alist= [1,3,4,5,3,2,1]
n = random.randint(0, len(alist)-1))
print(alist[n])
There is no problem in acheiving the goal, but it does not seem pythonic.
In python 3.6, a module called "secrets" was added. It describes as below.
"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."
Using the secrets module you can shorten the codes 2/3 as below.
import secrets
alist= [1,3,4,5,3,2,1]
print(secrets.choice(alist))
It looks much better, cleaner so pythonic.
'Programmer > Python & Django' 카테고리의 다른 글
How to check currently-used database in django? (0) | 2019.08.12 |
---|---|
Django 배포 후 DNS 설정 Welcome to nginx 페이지만 나온다면? (0) | 2018.11.08 |
(100-1)How to extract a random element from a python list. (0) | 2018.07.10 |
(100-1)파이썬 리스트에서 멤버 무작위 추출하기 (secret module) (0) | 2017.12.02 |
RSA 암호 알고리즘 정리 (0) | 2017.03.09 |
파이썬 프로젝트 1: 수열 직접 만들어 오름차수로 정렬하기 (0) | 2017.03.04 |