관리 메뉴

물 만날 물고기

[python] 내장함수 - random 모듈 본문

Python/파이썬 (python)

[python] 내장함수 - random 모듈

Lung Fish 2023. 1. 5. 16:34

🔍예상 검색어

더보기

# 파이썬 랜덤함수

# 파이썬 랜덤 모듈

# 랜덤으로 숫자 생성하기

# python random 

# random.random #random.randint

# python 무작위로 숫자 만들기 # 랜덤으로 숫자 만들기

# 랜덤으로 하나 선택 #랜덤으로 여러개 선택

모듈 불러오기

import random

1) random.random()

  • random() -> x in the interval [0, 1)
  • 0.0에서 1.0사이의 실수 중에서 난수값을 리턴
random.random()

>>> 0.6468876430600504

2) random.randint(a, b)

  • Return random integer in range [a, b], including both end points.  
  • a, b 사이의 정수 중에서 난수값을 리턴
  • a <= ? <= b
random.randint(1,10)

>>> 6

⚠️ randint는 a, b값이 모두 포함된다.

 

3) random.randrange(start, stop=None, step=1)

  • Choose a random item from range(start, stop[, step]).
  • This fixes the problem with randint() which includes the endpoint; in Python this is usually not what you want.
  • range(start, stop, step) 함수로 만들어지는 정수 중에서 난수값을 리턴
  • start <= ? <= stop
random.randrange(0, 10, 2) # [0,2,4,6,8] 중 하나를 출력

>>> 6

⚠️ randrange는 start 값은 포함되지만,  stop 값은 범위에 포함되지 않는다.

 

 

 

4) random.uniform(a, b)

  • Get a random number in the range [a, b) or [a, b] depending on rounding.
  • a, b 사이의 실수 중에서 난수값을 리턴함
  • a <= ?.??? <= b
random.uniform(50, 80)

>>> 53.262365385663685

 

5) random.choice(list)

  • Choose a random element from a non-empty sequence.
  • 매개변수로 (문자열, 튜플, 리스트) 형태를 받고, 그중에서 무작위로 하나를 선택하여 리턴함
data = [1, 2, 3, 4, 5]
random.choice(data)

>>> 2
name = ['오정남', '김서준', '윤유진', '송상훈', '박경숙']
random.choice(name)

>>> '윤유진'
name = ['오정남']
random.choice(name)

>>> '오정남'
random.choice('오정남')

>>> '정'

 

6) random.choices(data, k=n)

  • Return a k sized list of population elements chosen with replacement.
  • If the relative weights or cumulative weights are not specified, the selections are made with equal probability.
  • k값을 입력할 때 k=1, k=2, 이런식으로 k=n 이라고 표시해야지 오류가 발생되지 않음
name = ['오정남', '김서준', '윤유진', '송상훈', '박경숙']
random.choices(name, k=4)

>>> ['박경숙', '윤유진', '윤유진', '윤유진'] #중복되는 사람 있음
name = ['오정남', '김서준', '윤유진', '송상훈', '박경숙']
random.choices(name, k=10)

>>> ['박경숙', '윤유진', '송상훈', '박경숙', '윤유진', '김서준', '박경숙', '김서준', '윤유진', '김서준']

 

7) random.sample(list, n)

  • Chooses k unique random elements from a population sequence or set.
  • 매개변수로 문자열, 튜플, 리스트 또는 세트 타입 데이터를 입력 받고,  정한 개수만큼 무작위로 뽑아서 리턴
name = ['오정남', '김서준', '윤유진', '송상훈', '박경숙']
random.sample(name, 2) # k=2

>>> ['오정남', '김서준']
name = ['오정남', '김서준', '윤유진', '송상훈', '박경숙']
random.sample(name, 6) k가 리스트 개수보다 크면 에러 발생

>>> ValueError: Sample larger than population or is negative

⚠️ k가 리스트 개수보다 크면 에러 발생

 


# 참고자료

 

파이썬 랜덤함수 사용, random 모듈 알아보기

코딩을 하다 보면 random값이 필요할 때가 있습니다. 무작위로 뽑는다는 것은 통계에서 아주 중요한 의미를 가지고 있습니다. 특정 변수와 상관관계가 없기 때문에, sample을 뽑거나 테스트를 할 때

aplab.tistory.com

 

[Python] random 모듈 정리

random 모듈이란? Python에서 난수(random number)를 구할 수 있는 모듈입니다. 일부 자주 사용할 것 같은 함수들만 소개하겠습니다. random 모듈은 import random 한 뒤, random.함수이름() 을 통해 random 모듈에

wooono.tistory.com

 

[Python 3] random 모듈 (random, uniform , randint , randrange , choice , sample , shuffle)

random 모듈 random는 난수를 발생 시키는 모듈이다. 모듈에는 여러 함수가 존재한다. 모듈 임포트 >>> import random random() 함수 0.0에서 1.0 사이의 실수 중에서 난수값을 리턴 0.0 >> random.random() 0.5176390829

supermemi.tistory.com

 

파이썬 sample vs choices 의 차이를 알아봅시다.

python에는 random이 있습니다. 여기에 있는 메서드 중에서 sample과 choices의 차이를 알아봅시다. 먼저 예제 1번을 보겠습니다. 왠 리스트가 있는데요. li는 [1, 2, 3, 4, 5]입니다. 4번째 줄에서 rd.choices와

codingdog.tistory.com

 

Python 리스트 랜덤 추출 choice,sample,choices 사용 방법

파이썬 표준 라이브러리 random 모듈 함수 choice, sample, choices를 사용해 리스트 또는 튜플에서 요소를 랜덤으로 추출하는 방법을 알아보겠습니다. 우선 choice, sample, choices에 대해 간단히 살펴보겠습

ponyozzang.tistory.com