random 모듈은 의사 난수 생성을 위한 도구입니다. 시뮬레이션, 게임, 테스트 데이터 생성 등에 사용합니다. 보안용으로는 secrets 모듈을 사용하세요.
언제 이 치트시트를 보나?
- 무작위 숫자를 생성해야 할 때
- 리스트에서 랜덤 선택이 필요할 때
- 셔플, 샘플링이 필요할 때
핵심 함수
| |
최소 예제
1. 정수 난수
| |
2. 실수 난수
| |
3. 리스트에서 선택
| |
4. 가중치 선택
| |
5. 셔플
| |
6. 시드 설정 (재현 가능)
| |
7. 분포 함수
| |
8. 실용 예제
| |
9. 가중치 로또/가챠 시스템
| |
10. Random 인스턴스 (독립적 생성기)
| |
random vs secrets
| |
자주 하는 실수
1. sample에서 k가 너무 클 때
| |
2. 빈 시퀀스에서 choice
| |
3. shuffle 반환값
| |
한눈에 정리
| 함수 | 용도 | 예시 |
|---|---|---|
randint(a, b) | 정수 (a~b 포함) | randint(1, 6) |
random() | 0~1 미만 실수 | random() |
choice(seq) | 하나 선택 | choice(['a', 'b']) |
choices(seq, k=n) | n개 복원 선택 | choices([1,2,3], k=5) |
sample(seq, k=n) | n개 비복원 선택 | sample([1,2,3], k=2) |
shuffle(seq) | 제자리 섞기 | shuffle(list) |
seed(n) | 시드 설정 | seed(42) |
![Featured image of post [Python Cheatsheet] 48. random - 난수 생성과 무작위 선택](/post/python-cheatsheet/random-module-guide-efficient-random-number-generation-examples/wordcloud_hu_417e8d767bb12815.webp)
![[Python Cheatsheet] 46. math & statistics - 수학/통계 함수](/post/python-cheatsheet/math-statistics-functions-guide-essential-formulas-examples/wordcloud_hu_849c8affbe8bf7cf.webp)
![[Python Cheatsheet] 47. decimal & fractions - 정밀 수치 연산](/post/python-cheatsheet/decimal-fraction-precision-finance-scientific-guide/wordcloud_hu_a3f3b46f8083983b.webp)
![[Python Cheatsheet] 48. random - 난수 생성과 무작위 선택](/post/python-cheatsheet/random-module-guide-efficient-random-number-generation-examples/wordcloud_hu_7a47f96f9cd69d9f.webp)
![[Python Cheatsheet] 49. uuid - 고유 식별자 생성](/post/python-cheatsheet/unique-id-generation-uuid-module-guide/wordcloud_hu_d297d96d8e063614.webp)
![[Python Cheatsheet] 50. hashlib & secrets - 해시/보안 난수 패턴](/post/python-cheatsheet/hashlib-secrets-hash-random-security-tips-token-checksum-digest/wordcloud_hu_e76d052b870185b4.webp)
![[Python Cheatsheet] 51. os 심화 - 파일시스템과 프로세스](/post/python-cheatsheet/os-module-filesystem-process-management-guide/wordcloud_hu_73e247b068bbcc17.webp)
![[Python Cheatsheet] 21. Enum & Flag - 열거형 실전 패턴](/post/python-cheatsheet/enum-flag-intenum-strenum-auto-bitwise-guide-best-patterns/wordcloud_hu_c5e80eb17669433.webp)
![[Python Cheatsheet] 29. operator - 연산자 함수와 효율적 접근자](/post/python-cheatsheet/efficient-operator-module-guide-for-sorting-functional-patterns/wordcloud_hu_ccfe1db60a2f866a.webp)
![[Python Cheatsheet] 32. contextlib 심화 - suppress, redirect, ExitStack](/post/python-cheatsheet/contextlib-advanced-suppress-redirect-exitstack-nullcontext-examples/wordcloud_hu_63614113bfad58c2.webp)
![[Python Cheatsheet] 36. XML - ElementTree로 XML 파싱/생성](/post/python-cheatsheet/xml-elementtree-parse-edit-xpath-security-namespace-guide/wordcloud_hu_7317e644ad4bd8b8.webp)