random.random() : 0.0 이상 1.0 미만의 실수를 반환합니다.
import random
# 0.0 이상 1.0 미만의 난수 생성
result = random.random()
print(result) # 예: 0.7457397453918837
random.randint(a, b) : a 이상 b 이하의 정수(int)를 무작위로 반환합니다. 주의) 경계값 a, b가 포함됩니다.
import random
# 1 이상 10 이하의 정수 난수 생성
result = random.randint(1, 10)
print(result) # 예: 4
random.sample(population, k) : 주어진 리스트(population)에서 k개의 요소를 무작위로 비복원추출합니다.
import random
# 리스트에서 3개의 요소를 중복 없이 무작위로 선택
items = [1, 2, 3, 4, 5, 6]
result = random.sample(items, 3)
print(result) # 예: [2, 5, 6]
random.choice(seq) : 주어진 시퀀스(seq)에서 무작위로 하나의 요소를 반환합니다.
import random
# 리스트에서 무작위로 하나의 요소 선택
items = ['apple', 'banana', 'cherry']
result = random.choice(items)
print(result) # 예: 'banana'
random.choices(population, weights=None, k=1) : 주어진 리스트에서 가중치(weights)로 k개의 요소를 무작위로 복원추출합니다.
import random
# 가중치를 설정하여 무작위로 3개의 요소를 선택 (중복 허용)
items = ['apple', 'banana', 'cherry']
weights = [5, 1, 1] # 'apple'이 선택될 확률이 높음
result = random.choices(items, weights=weights, k=3)
print(result) # 예: ['apple', 'cherry', 'apple']
random.shuffle(x) : 리스트의 요소들을 무작위로 섞습니다. 원본 리스트가 변경됩니다.
import random
# 리스트의 요소를 무작위로 섞음
items = [1, 2, 3, 4, 5]
random.shuffle(items)
print(items) # 예: [3, 5, 1, 4, 2]
'프로그래밍 > Python 관련 정보' 카테고리의 다른 글
[Python - Frequently Used Code] pandas DataFrame 문자열 대체 (0) | 2025.02.04 |
---|---|
[Default variable is mutable] Warning (0) | 2025.01.30 |
[Python - Frequently Used Code] Class input argument (0) | 2024.11.22 |
[Python Programming 기초] __main__ (0) | 2024.11.11 |
[Pycharm Tips] Debugging (1) | 2024.11.10 |