Seleccione 50 elementos de la lista al azar para escribir en el archivo


Hasta ahora he descubierto cómo importar el archivo, crear nuevos archivos y aleatorizar la lista.

Estoy teniendo problemas para seleccionar solo 50 elementos de la lista al azar para escribir en un archivo?

def randomizer(input,output1='random_1.txt',output2='random_2.txt',output3='random_3.txt',output4='random_total.txt'):

#Input file 
    query=open(input,'r').read().split()
    dir,file=os.path.split(input)

    temp1 = os.path.join(dir,output1)
    temp2 = os.path.join(dir,output2)
    temp3 = os.path.join(dir,output3)
    temp4 = os.path.join(dir,output4)


    out_file4=open(temp4,'w')

    random.shuffle(query)

    for item in query:
        out_file4.write(item+'\n')   

Así que si el archivo de aleatorización total fuera

example:

random_total = ['9','2','3','1','5','6','8','7','0','4']

Me gustaría 3 archivos (out_file1 / 2 / 3) con el primer conjunto aleatorio de 3, el segundo conjunto aleatorio de 3 y el tercer conjunto aleatorio de 3 (para este ejemplo, pero el que quiero crear debe tener 50)

random_1 = ['9','2','3']
random_2 = ['1','5','6']
random_3 = ['8','7','0']

Así que el último' 4 ' será no ser incluido lo cual está bien.

¿Cómo puedo seleccionar 50 de la lista que me aleatorizado ?

Aún mejor, ¿cómo podría seleccionar 50 al azar de la lista original ?

Author: b4hand, 2013-03-20

4 answers

Si la lista está en orden aleatorio, solo puede tomar los primeros 50.

De lo contrario, use

import random
random.sample(the_list, 50)

random.sample texto de ayuda:

sample(self, population, k) method of random.Random instance
    Chooses k unique random elements from a population sequence.

    Returns a new list containing elements from the population while
    leaving the original population unchanged.  The resulting list is
    in selection order so that all sub-slices will also be valid random
    samples.  This allows raffle winners (the sample) to be partitioned
    into grand prize and second place winners (the subslices).

    Members of the population need not be hashable or unique.  If the
    population contains repeats, then each occurrence is a possible
    selection in the sample.

    To choose a sample in a range of integers, use xrange as an argument.
    This is especially fast and space efficient for sampling from a
    large population:   sample(xrange(10000000), 60)
 146
Author: John La Rooy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-26 13:29:43

Una forma fácil de seleccionar elementos aleatorios es barajar y luego cortar.

import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables
 17
Author: Mani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-30 01:09:08

Creo que random.choice() es una mejor opción.

import numpy as np

mylist = [13,23,14,52,6,23]

np.random.choice(mylist, 3, replace=False)

La función devuelve una matriz de 3 valores elegidos aleatoriamente de la lista

 16
Author: Moeen MH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-25 22:50:08

Supongamos que su lista tiene 100 elementos y desea elegir 50 de ellos de manera aleatoria. Estos son los pasos a seguir:

  1. Importa las bibliotecas
  2. Crear la semilla para generador de números aleatorios, lo he puesto en 2
  3. Preparar una lista de números de los que recoger de una manera aleatoria
  4. Haga las elecciones aleatorias de la lista de números

Código:

from random import seed
from random import choice

seed(2)
numbers = [i for i in range(100)]

print(numbers)

for _ in range(50):
    selection = choice(numbers)
    print(selection)
 0
Author: AlketCecaj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-14 09:22:04