Python 라이브러리 - random

공식 문서

source code 링크

random

random은 난수를 생성할 때 사용하는 모듈입니다.

아래는 1 ~ 45 사이 숫자 중 임의의 숫자를 생성하는 예시 코드입니다.

import random 

result = []
while len(result) < 6:
    num = random.randint(1, 45)     # 1 ~ 45 사이의 정수 생성
    if num not in result:           # 중복 숫자 방지
        result.append(num)
print(result)       # [7, 20, 21, 25, 45, 43]

random.randint(a, b)는 a와 b사이의 무작위 정수를 생성하는 함수입니다.

shuffle과 choice

shuffle

리스트 요소를 무작위로 섞고 싶다면 random.shuffle() 함수를 사용합니다.

a = [1, 2, 3, 4]
random.shuffle(a)
print(a)        # [1, 4, 3, 2]

choice

리스트 요소에서 무작위로 하나를 선택하려면 random.choice()를 사용합니다.

print(random.choice(a))     # 4
print(random.choice(a))     # 2

 

 

 

 

'Python > Python' 카테고리의 다른 글

Python 라이브러리 - operator.itemgetter  (0) 2023.05.18
Python 라이브러리 - statistics  (0) 2023.05.17
Python 라이브러리 - fractions  (0) 2023.05.17
Python 라이브러리 - decimal  (0) 2023.05.16
Python 라이브러리 - math  (0) 2023.05.16