mercredi 11 décembre 2019

Python 3.5 loop to generate a new list each iteration

I'm trying to write some code that (pseudo-randomly) generates a list of 7 numbers. I have it working for a single run. I'd like to be able to loop this code to generate multiple lists, which I can output to a txt file (I don't need help with this I'm quite comfortable working with i/o and files :)

I've got this code:

import random

pool = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
        31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,
        58,59]

list1 = []

def spinAndPrune(x):
        random.shuffle(pool)
        #random.seed(random.randint(1, 50000000))
        current_choice = random.choice(pool)
        list1.append(current_choice)
        pool.remove(current_choice)
        random.shuffle(pool)

run_it = [spinAndPrune(pool) for x in range(7)]

This works nicely as a one-time operation, however I want to loop it to create as many lists as required. At first I thought of something like this (which I guessed wasn't going to work but here it is anyway):

def repeater():
    for i in range(19):
            a = [selectAndPrune(pool) for x in range(7)]
            print(list1)


repeater()

Of course this gives:

IndexError: Cannot choose from an empty sequence

I think I understand why this is happening, but I'm not sure what the answer to my problem is... Many thanks in advance to any and all that chime in I'm sure there's something obvious I'm not seeing.




Aucun commentaire:

Enregistrer un commentaire