muestra() es una función incorporada de módulo aleatorio en Python que devuelve una lista de longitud particular de elementos elegidos de la secuencia, es decir, lista, tupla, cadena o conjunto. Se utiliza para muestreo aleatorio sin reemplazo.
Sintaxis: muestra.aleatoria(secuencia, k)
Parámetros:
secuencia : Puede ser una lista, tupla, cadena o conjunto.
k : Un valor entero, especifica la longitud de una muestra.Devoluciones: k longitud nueva lista de elementos elegidos de la secuencia.
Código #1: Implementación simple de la función sample().
algoritmo de Kruskal
# 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> ))> |
>
>
Producción:
[2, 3, 5]>
Código #2: Uso básico de la función sample().
cadena de conversión de Java a int
# 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> ))> |
>
>
Producción:
fotos de icloud a android
With list: [3, 1, 2] With string: ['e', 'f', 'G', 'G'] With tuple: ['ankit', 'portal', 'geeks', 'computer'] With set: ['b', 'd', 'c']>
Nota: La salida será diferente cada vez, ya que devuelve un elemento aleatorio.
Código #3: Generar excepción
Si el tamaño de la muestra, es decir, k, es mayor que el tamaño de la secuencia, Error de valor es elevado.
# Python3 program to demonstrate the> # error of sample() function.> import> random> > list1> => [> 1> ,> 2> ,> 3> ,> 4> ]> > # exception raised> print> (random.sample(list1,> 5> ))> |
>
>
Producción:
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>