【问题标题】:How do I initialize and fill in a list of lists of different lengths?如何初始化和填写不同长度的列表?
【发布时间】:2016-07-23 04:46:35
【问题描述】:

我正在编写一个模拟某个电视节目的小型 Python 程序(这是为了好玩,请不要评判我)。

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

为了进一步解释第二个参数,我举个例子。假设皇后区需要分成 5 人和 6 人的 2 队。那么 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)

现在,我打算用queenList 填充teamShuffledList,但是teamShuffledList 有不同长度的列表。有没有简单的方法来跟踪不同的长度?任何帮助将不胜感激,非常感谢。

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

【问题讨论】:

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


    【解决方案1】:
    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
    

    没有必要“初始化”任何东西。

    【讨论】:

    • 非常感谢! (对不起,我还是个业余爱好者)
    【解决方案2】:
    def sortIntoTeams(contest_obj, numTeams):
        counter = 0
        teams = []
        for k in numTeams:
            teams.append(contest_obj[counter:counter + k])
            counter = counter + k
        return teams
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多