Python: how to create a list of lists with increas

2019-05-23 01:45发布

问题:

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?

回答1:

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.