Python | fonction random.sample()

échantillon() est une fonction intégrée de module aléatoire en Python qui renvoie une liste d'éléments de longueur particulière choisis dans la séquence, c'est-à-dire une liste, un tuple, une chaîne ou un ensemble. Utilisé pour un échantillonnage aléatoire sans remplacement.

Syntaxe : random.sample (séquence, k)

Paramètres:
séquence : Peut être une liste, un tuple, une chaîne ou un ensemble.
k : Une valeur entière, elle spécifie la longueur d'un échantillon.

Retour: k longueur nouvelle liste d’éléments choisis dans la séquence.

Code n°1 : Implémentation simple de la fonction sample().




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

Sortir:

[2, 3, 5] 


Code n°2 : Utilisation de base de la fonction sample().




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

Sortir:

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

Note: La sortie sera différente à chaque fois car elle renvoie un élément aléatoire.

Code n°3 : Lever une exception

Si la taille de l'échantillon, c'est-à-dire k, est supérieure à la taille de la séquence, ValeurErreur est relevé.




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

Sortir:

 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