logo

파이썬 | 무작위.샘플() 함수

견본() 내장된 기능입니다 무작위 모듈 Python에서는 시퀀스, 즉 목록, 튜플, 문자열 또는 집합에서 선택된 항목의 특정 길이 목록을 반환합니다. 교체 없이 무작위 샘플링에 사용됩니다.

구문: 무작위.샘플(시퀀스, k)



매개변수:
순서 : 목록, 튜플, 문자열 또는 집합이 될 수 있습니다.
케이 : 정수 값으로 샘플의 길이를 지정합니다.

보고: k 길이의 시퀀스에서 선택된 요소의 새 목록입니다.

코드 #1: Sample() 함수의 간단한 구현.



김프를 jpg로 내보내기






# Python3 program to demonstrate> # the use of sample() function .> > # import random> from> random>import> sample> > # Prints list of random items of given length> list1>=> [>1>,>2>,>3>,>4>,>5>]> > print>(sample(list1,>3>))>

>

>

산출:

[2, 3, 5]>


코드 #2: Sample() 함수의 기본 사용법.




텍스트 감싸기용 CSS

# Python3 program to demonstrate> # the use of sample() function .> > # import random> import> random> > > # Prints list of random items of> # length 3 from the given list.> list1>=> [>1>,>2>,>3>,>4>,>5>,>6>]> print>(>'With list:'>, random.sample(list1,>3>))> > # Prints list of random items of> # length 4 from the given string.> string>=> 'techcodeview.com'> print>(>'With string:'>, random.sample(string,>4>))> > # Prints list of random items of> # length 4 from the given tuple.> tuple1>=> (>'ankit'>,>'geeks'>,>'computer'>,>'science'>,> >'portal'>,>'scientist'>,>'btech'>)> print>(>'With tuple:'>, random.sample(tuple1,>4>))> > > # Prints list of random items of> # length 3 from the given set.> set1>=> {>'a'>,>'b'>,>'c'>,>'d'>,>'e'>}> print>(>'With set:'>, random.sample(set1,>3>))>

>

>

산출:

안드로이드의 사과 이모티콘
With list: [3, 1, 2] With string: ['e', 'f', 'G', 'G'] With tuple: ['ankit', 'portal', 'geeks', 'computer'] With set: ['b', 'd', 'c']>

메모: 무작위 항목을 반환하므로 출력은 매번 달라집니다.

코드 #3: 예외 발생

샘플 크기, 즉 k가 시퀀스 크기보다 큰 경우, 값오류 제기됩니다.




# Python3 program to demonstrate the> # error of sample() function.> import> random> > list1>=> [>1>,>2>,>3>,>4>]> > # exception raised> print>(random.sample(list1,>5>))>

>

>

산출:

 Traceback (most recent call last): File 'C:/Users/user/AppData/Local/Programs/Python/Python36/all_prgm/geeks_article/sample_method_article.py', line 8, in print(random.sample(list1, 5)) File 'C:UsersuserAppDataLocalProgramsPythonPython36lib
andom.py', line 317, in sample raise ValueError('Sample larger than population or is negative') ValueError: Sample larger than population or is negative>