George Juarez George Juarez - 1 year ago 162
Python Question

How do I initialize and fill in a list of lists of different lengths?

I'm writing a small Python program that will simulate a certain TV show (it's for fun guys ok please don't judge me).

In this program, I am trying to randomly sort the contestants into a list of lists (to emulate a Team Challenge, as you may say). I wrote a function that (is intended) to take in an unsorted list of Contestant objects (because I want to access the name attribute of each Contestant object) and a list that contains the information about the sizes of each individual list in the 2D list I intend to return in the end.

To further explain the second parameter, I'll give an example. Let's say the Queens need to be divided into 2 teams of 5 and 6. The numTeams will then be [5,6].

This is full function that I have written so far:

def sortIntoTeams(contest_obj, numTeams):
# where I will eventually store all the names of the individuals
queenList = []
# creates 2D list, however, I just initialized the first subscript
# part, so to speak
teamShuffledList = len(numTeams) * [[None]]
# this was just a test, but I made another for loop to
# fill the second subscript part of the 2D list, so to speak too
for i in range(0, len(numTeams)):
count = numTeams[i]
teamShuffledList[i] = count * [0]
# for loop to fill queenList with all the names of the Queen
# objects in the contest_obj
for i in range(0, countRemaining(contest_obj)):
# from random import shuffle, to shuffle queenList

Now, what I intend to do is fill the teamShuffledList with queenList, but the teamShuffledList has lists of different lengths. Is there any easy way to keep tracks of the different lengths? Any help would be greatly appreciated, thanks so much.

EDIT: Even though it's sorta self-explanatory, the countRemaining(contest_obj) is a different function that I wrote that just counts the remaining contestant objects in the list.

Answer Source
def sortIntoTeams(contest_obj, numTeams):
    # Create a randomly-ordered copy of the contestants' names
    random_contestants = [ for x in contest_obj]
    result = []
    for teamsize in numTeams:
        # Take the first <teamsize> contestants from the list
        # Remove those contestants, since they now have a team
        random_contestants = random_contestants[teamsize:]
    return result

There is no need to "initialize" anything.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download