Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
150 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...