vendredi 11 novembre 2016

Randomly select X number of lists from a list of lists

I have something like the following:

pen = [1, 2, 3, 4]
pencil = [2,3,4,5]
paper = [3,4,5,6]
group_of_items = [pen, pencil, paper]

I want to randomly select a certain number of lists from this list of lists so that the result is something like this:

[pencil, pen]

I found the following from another question (altered to match my situation).

import random

pen = [1, 2, 3, 4]
pencil = [2,3,4,5]
paper = [3,4,5,6]

group_of_items = [pen, pencil, paper]

num_to_select = 2
list_of_random_items = random.sample(group_of_items, num_to_select)
print(list_of_random_items)

It gives something like this.

[[2, 3, 4, 5], [1, 2, 3, 4]]

So, it's close but no cigar. I also found this.

import numpy as np

pen = [1, 2, 3, 4]
pencil = [2,3,4,5]
paper = [3,4,5,6]
group_of_items = [pen, pencil, paper]
num_to_select = 2

random_list = np.random.choice(group_of_items, num_to_select, replace=False)

print(random_list)

But it doesn't work with a list of lists (multi-dimensional).

How can I accomplish my goal?

Oh, and I don't want any repeats.

Note: my coding experience is rather limited. I mostly copy and paste what I find online, only making small changes.




Aucun commentaire:

Enregistrer un commentaire