본문 바로가기
Python/파이썬 라이브러리

파이썬 random 라이브러리

by PySun 2023. 7. 31.
반응형

 

random 라이브러리:

random 라이브러리는 난수(랜덤 숫자)를 생성하는 함수들을 제공하는 라이브러리입니다. 다양한 난수 생성 함수와 시퀀스 조작 함수를 포함하고 있습니다.

난수 생성 함수:

  1. random.random(): 0 이상 1 미만의 실수 난수를 반환합니다.
  2. random.uniform(a, b): a 이상 b 이하의 실수 난수를 반환합니다.
  3. random.randint(a, b): a 이상 b 이하의 정수 난수를 반환합니다.
  4. random.randrange(start, stop, step): start 이상 stop 미만의 정수 난수를 step 간격으로 반환합니다.
  5. random.choice(sequence): 시퀀스(리스트, 문자열 등)에서 임의의 요소를 반환합니다.
import random

# random.random()
random_float = random.random()
print("random():", random_float)  # 출력: 0.0 이상 1.0 미만의 임의의 실수

# random.uniform()
random_uniform = random.uniform(1, 10)
print("uniform(1, 10):", random_uniform)  # 출력: 1 이상 10 미만의 임의의 실수

# random.randint()
random_int = random.randint(1, 100)
print("randint(1, 100):", random_int)  # 출력: 1 이상 100 이하의 임의의 정수

# random.randrange()
random_range = random.randrange(0, 100, 5)
print("randrange(0, 100, 5):", random_range)  # 출력: 0 이상 100 미만의 5의 배수

# random.choice()
my_list = [1, 2, 3, 4, 5]
random_choice = random.choice(my_list)
print("choice:", random_choice)  # 출력: my_list 중 임의의 요소

시퀀스 조작 함수:

  1. random.shuffle(sequence): 시퀀스의 요소를 무작위로 섞습니다.
  2. random.sample(population, k): 인구에서 중복되지 않는 k개의 요소를 무작위로 선택하여 리스트로 반환합니다.
import random

# random.shuffle()
random.shuffle(my_list)
print("shuffle:", my_list)  # 출력: my_list 요소들을 무작위로 섞음

# random.sample()
population = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random_sample = random.sample(population, 3)
print("sample:", random_sample)  # 출력: population 중 3개의 요소를 무작위로 선택하여 리스트로 반환

위의 함수들을 활용하면 난수 생성으로 다양한 작업을 간단하고 효율적으로 수행할 수 있습니다. 이러한 라이브러리들은 데이터 분석, 시뮬레이션 등 다양한 분야에서 매우 유용하게 활용됩니다.
 

반응형

'Python > 파이썬 라이브러리' 카테고리의 다른 글

파이썬 datetime 라이브러리  (0) 2023.08.01
파이썬 math 라이브러리  (0) 2023.07.29