paraugs () ir iebūvēta funkcija izlases modulis Python, kas atgriež noteikta garuma vienumu sarakstu, kas izvēlēts no secības, t.i., saraksts, kortežs, virkne vai kopa. Izmanto izlases veida paraugu ņemšanai bez aizstāšanas.
Sintakse : random.sample(sequence, k)
Parametri:
secība : var būt saraksts, virkne, virkne vai kopa.
k : Vesela skaitļa vērtība, kas norāda parauga garumu.
Atgriež: k garuma jauns no secības izvēlēto elementu saraksts.
Kods #1: Funkcijas sample() vienkārša ieviešana.
kad iznāca win 7
# 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>))> |
>
>
Izvade:
[2, 3, 5]>
Kods #2: Funkcijas sample() pamata izmantošana.
lateksa teksta izmēri
# 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>))> |
>
>
Izvade:
dziedināt rīks gimp
With list: [3, 1, 2] With string: ['e', 'f', 'G', 'G'] With tuple: ['ankit', 'portal', 'geeks', 'computer'] With set: ['b', 'd', 'c']>
Piezīme: Izvade katru reizi būs atšķirīga, jo tā atgriež nejaušu vienumu.
Kods #3: Paaugstināt izņēmumu
Ja izlases lielums, t.i., k ir lielāks par secības lielumu, ValueError tiek pacelts.
# Python3 program to demonstrate the> # error of sample() function.> import> random> > list1>=> [>1>,>2>,>3>,>4>]> > # exception raised> print>(random.sample(list1,>5>))> |
>
>
Izvade:
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>