[Error][Python] ValueError: Sample larger than population or is negative

·2023년 3월 20일
0

[Trouble Shooting]

목록 보기
3/8
post-thumbnail

에러 타입

  • ValueError: Sample larger than population or is negative

에러 코드

age = random.sample(range(1, 100), 100)

에러 상황

  • 1부터 99까지 수 중에서 중복을 포함하면서 100개를 뽑아 리스트로 만들기위해 random.sample() 함수로 코드 작성 중 에러발생

에러 원인

  • random.sample(population, k, *, counts=None)
  • Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
  • If the sample size is larger than the population size, a ValueError is raised.
  • 반환된 리스트의 값은 유니크한 요소로만 이루어지기 때문에 sample size 보다 range 사이즈가 더 커야함

에러 해결

  • 1부터 99까지 수 중에서 중복을 포함하면서 100개를 뽑아 리스트로 만드는게 목표이기 때문에 sample() 함수로는 불가함
  • 중복이 포함되는 random.choices() 함수를 이용해서 해결
  • random.choices(population, weights=None, *, cum_weights=None, k=1)
    #변경 전
       age = random.sample(range(1, 100), 100)

    #변경 후
       ages = random.choices(range(1, 100), k=100)


profile
개발하고싶은사람

0개의 댓글