Python | random.sample() funktion

prøve() er en indbygget funktion af tilfældigt modul i Python, der returnerer en bestemt længde liste over elementer valgt fra sekvensen, dvs. liste, tuple, streng eller sæt. Anvendes til stikprøveudtagning uden udskiftning.

Syntaks: random.sample(sekvens, k)

Parametre:
rækkefølge : Kan være en liste, tupel, streng eller sæt.
k : En heltalsværdi, den angiver længden af ​​en prøve.

Vender tilbage: k længde ny liste over elementer valgt fra sekvensen.

Kode #1: Simpel implementering af sample() funktion.




# 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> ))>

Produktion:

[2, 3, 5] 


Kode #2: Grundlæggende brug af sample() funktion.




# 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> ))>

Produktion:

With list: [3, 1, 2] With string: ['e', 'f', 'G', 'G'] With tuple: ['ankit', 'portal', 'geeks', 'computer'] With set: ['b', 'd', 'c'] 

Bemærk: Output vil være forskelligt hver gang, da det returnerer en tilfældig vare.

Kode #3: Hæve Undtagelse

Hvis prøvestørrelsen, dvs. k er større end sekvensstørrelsen, ValueError er hævet.




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

Produktion:

 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