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