Nuno Chicória Nuno Chicória - 7 months ago 23
Python Question

Loop Through a Random List Generator

This code I'm using is part of a bigger on I'm writing. In this part I create a random list of smaller size using a previous list of larger size. Is there a way to loop this random list creator x times and for it to save something like list1, list2, list3, ..., listx?

The code I'm using is this one:

positive_classifier = [
positive[i] for i in sorted(
random.sample(xrange(len(positive)), n_prot_classifier)) ]

And positive is the bigger list I'm accessing and n_prot_classifier is a variable that I defined earlier that defines the length of the new list.


You can create a list of lists by extending your code a bit. This will create a list containing list_count lists, each containing random elements from positive.

list_count = 5
positive_classifier = [
    [positive[i] for i in sorted(random.sample(xrange(len(positive)), n_prot_classifier))] 
    for _ in range(list_count)

Be aware the positive_classifier now is a list of lists, not a simple list as before.