2

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?

4
  • how many integers should contain each list ? can two different lists have two same numbers ? Commented Oct 20, 2016 at 16:17
  • l1 has 2 values, l2 has 4 values, l3 has 6, all the way to l10 which has 20. Yes, two different lists can have two same numbers. What matters is that in each list you don't have repetitions. Commented Oct 20, 2016 at 16:18
  • Can can 2 sublists have a number that is in both of them? Commented Oct 20, 2016 at 16:28
  • Yes, sure they can. Commented Oct 20, 2016 at 16:28

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Well, fancy stuff but I got an error: TypeError: random_sample() takes at most 1 positional argument (2 given). Btw thanks for explaining!
Works for me on python 2.7. What version of python are you using? Can you post the full traceback?
also, where is the random_sample method defined? That's not the same as the random.sample method I'm using.
FWIW, your masterlist won't contain unique random integers. But that's easy enough to do by building a set in a while loop & then converting the set to a list.
Yep, sorry it was just for an example list of 'things'. The questioner states they already have that list. I'll change it to a range for clarity.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.