-1

I have a list with the following items

l = [11.1, 22.2, 33.3, 11.1, 33.3, 33.3, 22.2, 55.5]

Each item is a multiple of 11.1 and the length of the list is 8. I would like to generate another list of 30 items with values 11.1, 22.2, 33.3, 55.5 present in the original list l.

I would like to know how to populate data from the list l to l_new.

Natasha
  • 937
  • 2
  • 13
  • 30

1 Answers1

1

You can use the random module to do it:

import random

l = [11.1, 22.2, 33.3, 11.1, 33.3, 33.3, 22.2, 55.5]

l_new = [random.choice(l) for _ in range(0, 30)]
print(l_new)

#OUTPUT:
#[11.1, 11.1, 22.2, 33.3, 22.2, 11.1, 33.3, 11.1, 55.5, 11.1, 33.3, 22.2, 55.5, 22.2, 22.2, 33.3, 11.1, 11.1, 33.3, 22.2, 33.3, 11.1, 11.1, 33.3, 22.2, 33.3, 33.3, 11.1, 33.3, 22.2]

l_new = random.choices(l, k=30)
print(l_new)

#OUTPUT:
#[11.1, 33.3, 33.3, 55.5, 33.3, 33.3, 55.5, 11.1, 22.2, 11.1, 55.5, 11.1, 11.1, 55.5, 22.2, 22.2, 22.2, 33.3, 11.1, 33.3, 55.5, 55.5, 33.3, 11.1, 11.1, 55.5, 22.2, 22.2, 11.1, 22.2]

The first solution l_new = [random.choice(l) for _ in range(0, 30)] use list comprehension and the random.choice() function that select one item from l for each iteration.

The second solution l_new = random.choices(l, k=30) just call the choices() function and let it generate the list, you have to specify the k that is the number of element to select.


There is another way that require the numpy module:

import numpy

l = [11.1, 22.2, 33.3, 11.1, 33.3, 33.3, 22.2, 55.5]

l_new = list(numpy.random.choice(l, size=30))
print(l_new)

#OUTPUT:
#[11.1, 33.3, 11.1, 22.2, 33.3, 22.2, 22.2, 33.3, 55.5, 33.3, 22.2, 33.3, 22.2, 55.5, 33.3, 33.3, 33.3, 55.5, 33.3, 11.1, 11.1, 11.1, 55.5, 11.1, 33.3, 33.3, 22.2, 22.2, 33.3, 22.2]

The list is generated by numpy.random.choice

Carlo Zanocco
  • 1,796
  • 3
  • 14
  • 25
  • I would like to know if we can fix the seed while using `numpy.random.choice`. Thanks a lot for the solution posted. – Natasha Oct 09 '20 at 08:32
  • This should do it: https://stackoverflow.com/a/52991726/5532710 – Carlo Zanocco Oct 09 '20 at 08:34
  • `from numpy.random import MT19937 from numpy.random import RandomState, SeedSequence rs = RandomState(MT19937(SeedSequence(123456789))) # Later, you want to restart the stream rs = RandomState(MT19937(SeedSequence(987654321)))` is provided [here](https://numpy.org/doc/stable/reference/random/generated/numpy.random.seed.html). I am not sure how to use this in the answer posted. Could you please help? – Natasha Oct 09 '20 at 08:51
  • Can you create a new question regarding this please and explain what you want to achieve? – Carlo Zanocco Oct 09 '20 at 08:52
  • https://stackoverflow.com/questions/64276987/how-to-fix-the-seed-while-using-random-choice – Natasha Oct 09 '20 at 09:07