如何初始化并填写不同长度的列表列表?

时间:2016-07-23 04:46:35

标签: python arrays list sorting python-3.x

我正在编写一个小型的Python程序,可以模拟某个电视节目(这对于有趣的人来说好吧请不要评判我)。

在这个程序中,我试图将参赛者随机排序到一个列表列表中(如您所说,模拟团队挑战)。我编写了一个函数(用于)接收未分类的参赛者对象列表(因为我想访问每个参赛者对象的名称属性)以及一个列表,其中包含有关2D列表中每个列表大小的信息我打算最后回来。

为了进一步解释第二个参数,我举一个例子。假设皇后区需要分为5队和6队。然后,numTeams将为[5,6]。

这是我到目前为止所写的全部功能:

    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)):
              queenList.append(contest_obj[i].name)
         # from random import shuffle, to shuffle queenList
         shuffle(queenList)

现在,我打算用teamList填充teamShuffledList,但teamShuffledList有不同长度的列表。有没有简单的方法来保持不同长度的轨道?非常感谢任何帮助,非常感谢。

编辑:虽然它有点不言自明,但countRemaining(contest_obj)是我写的一个不同的函数,它只计算列表中剩余的参赛者对象。

2 个答案:

答案 0 :(得分:0)

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

无需“初始化”任何内容。

答案 1 :(得分:0)

def sortIntoTeams(contest_obj, numTeams):
    counter = 0
    teams = []
    for k in numTeams:
        teams.append(contest_obj[counter:counter + k])
        counter = counter + k
    return teams