두부찌개 파이썬( Tofusoup python)

블로그 이미지

tofusoup429

파이썬에 대한 정보를 공유하는 개인 블로그입니다.

secrets 모듈을 사용해 리스트에서 무작위 item 추출하는 방법 (Extracting a random member from a list)

Regular Python 2017. 12. 2. 11:14

리스트에서 무작위로 배열안의 멤버를 추출하는 법을 소개한다.

(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
Posted by tofusoup429
블로그 이미지

파이썬에 대한 정보를 공유하는 개인 블로그입니다.

by tofusoup429

공지사항

    최근...

  • 포스트
  • 댓글
  • 트랙백
  • 더 보기

태그

  • 파이썬
  • kivy
  • 키비
  • converting stringto list
  • GUI
  • AST
  • Python

글 보관함

«   2025/07   »
일 월 화 수 목 금 토
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

링크

카테고리

Python (9)
Regular Python (3)
Django Python (1)
Configuration (2)
Kivy Project (0)
project1. TimerApp (0)
기타 (2)

카운터

Total
Today
Yesterday
방명록 : 관리자 : 글쓰기
tofusoup429's Blog is powered by daumkakao
Skin info material T Mark3 by 뭐하라
favicon

두부찌개 파이썬( Tofusoup python)

파이썬에 대한 정보를 공유하는 개인 블로그입니다.

  • 태그
  • 링크 추가
  • 방명록

관리자 메뉴

  • 관리자 모드
  • 글쓰기
  • Python (9)
    • Regular Python (3)
    • Django Python (1)
    • Configuration (2)
    • Kivy Project (0)
      • project1. TimerApp (0)
    • 기타 (2)

카테고리

PC화면 보기 티스토리 Daum

티스토리툴바