Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select 50 items from list at random to write to file

People also ask

How can I randomly select an item from a list?

Use the random. sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.

How do you select multiple random elements in a list Python?

You can use random. randint() and random. randrange() to generate the random numbers, but it can repeat the numbers. To create a list of unique random numbers, we need to use the sample() method.

How do I print a random item from a list in Python?

sample() Method to Randomly Select Elements From a List. Python has a built-in function called random. sample(). The random module contains the random.

How do you randomly select an array in Python?

The numpy. random. choice() function is used to get random elements from a NumPy array.


If the list is in random order, you can just take the first 50.

Otherwise, use

import random
random.sample(the_list, 50)

random.sample help text:

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)

One easy way to select random items is to shuffle then slice.

import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables

I think random.choice() is a better option.

import numpy as np

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

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

the function returns an array of 3 randomly chosen values from the list


  1. we have 3 samples ('orange','mango','apple'). Created series, should contain 7 elements & randomly selected from list.

    random.choice
    import random
    
    import numpy as np
    
    fruits = ['orange','mango','apple']
    
    np.random.choice(fruits, 7, replace=True)
    

    Output

    array(['orange', 'mango', 'apple', 'orange', 'orange', 'mango', 'apple'],
          dtype='<U6')
    
  2. Random selection from list (less than 3 values)

    random.sample
    import random
    
    random.sample(fruits, 3)