Say I have a list of 200 positive, unique, random integers called masterlist
.
I want to generate a list of 10 lists called container
so that: l1
has 2 random numbers coming from masterlist
, repetitions excluded; l2
has 4 elements, l3
has 6 elements, and so forth.
I know I can create my container
list like this:
comb=[[] for i in range(10)]
and that I can select a random value from a list using random.choice()
.
What is the best Pythonic way to nest the populating process of these 10 lists, so that I create one list, append the correct number of values checking that there are no repetitions, and proceed on to the next?
EDIT
This is my attempt:
comb=[[] for i in range(10)]
for j in range(1,11):
for k in range(0,2*j):
comb[j][k].append(random.choice(masterlist))
What is wrong with this?
This should do the trick:
import random
masterlist = [i for i in range(200)] # For example
container = [
random.sample(masterlist, l)
for l in range(2, 21, 2)
]
The container is made up of a list comprehension, setting the variable l
to 2, 4, 6 ... 18, 20 using the range()
call. Within each 'loop' of the comprehension, the built in random.sample()
call does the sampling-without-replacement that you're after.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.