Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

python 3.x - Populate data from a list

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...