-4

还,

人= ['保罗','弗朗索瓦','安德鲁','苏','史蒂夫','阿诺德','汤姆','丹尼','尼克','安娜','丹','黛安' , '米歇尔', '杰米', '凯伦']

num_teams = 4

L 应包含 4 个子列表,其中包含 0,1,2,3,0,1,2,3 格式的元素索引

 def form teams(people, num_teams):

   '''make num_teams teams out of the names in list people by counting off. people in a list of people's name(strs) and num_teams(an int >= 1) is the desired
   number of teams. Return a list of lists of names, each sublist representing a team.'''

 L= []
# Make an outer list
 for i in range(num_teams):
       L.append([])
# make an i th number of sublist according to the range

for team in range(num_teams) #in this case 0,1,2,3
      for i in range(0, len(people), num_teams) #start from 0 to len(people) which in this case is 15 and  by taking 0,1,2,3, steps 
          if (team + i) < len(people): <---??????
               L[team].append(people[team+i]) <---??????

 return L
 print(L)

 [['paul', 'steve', 'nick', 'michelle'],['francois','arnold','anna','jeremy'],     ['andrew','tom','dan','karen'],['sue','danny','diane']

有人可以解释我放置的那些吗?关于它,我是否正确理解了概念?

4

1 回答 1

0

我不太确定您要达到什么目的,但这也许可以达到您的目的:

print ( [ [x for i, x in enumerate (people) if i % num_teams == y] for y in range (num_teams) ] )

使用您的人员数组和 num_teams = 4,输出:

[['paul', 'steve', 'nick', 'michelle'], ['francois', 'arnold', 'anna', 'jermy'], ['andrew', 'tom', 'dan', 'karen'], ['sue', 'danny', 'diane']]

当 num_teams = 3 时,输出为:

[['paul', 'sue', 'tom', 'anna', 'michelle'], ['francois', 'steve', 'danny', 'dan', 'jermy'], ['andrew', 'arnold', 'nick', 'diane', 'karen']]

.

编辑:6个问号

用问号标记的第一行检查是否team + i在 list 的范围内people,以确保在下一个 likepeople[team+i]中不会失败。

用问号标记的第二行将列表中位置的元素附加team+ipeople相应团队的列表中。当我采取 num_teams 范围内的步骤时,您进入第一队(索引为 0)第 0、num_teams-th、2num_teams-th 等人,进入第二队(索引 1)第 1、(num_teams+1 )-th, (2num_teams+1)-the, etc person,依此类推,适用于所有团队。

但请不要使用此代码。它使事情变得过于复杂。您发布的代码的整个功能可以更清楚地表达。

.

编辑2:

您作为人类应用的算法是将所有人排成一排并在他们之前通过计数 0 1 2 3 0 1 2 3 0...(正如您已经说过的)。您可以像这样表达地实现它:

def makeTeams (people, teamCount):
    teams = []
    for i in range (teamCount): teams.append ( [] )

    #You can write the above two lines as this: teams = [ [] for x in range (teamCount) ]

    curTeam = 0
    #Now walk past the line of people:
    for person in people:
        #Add person to current team
        teams [curTeam].append (person)
        #Add 1 to the team index
        curTeam += 1
        #If you have counted too far, set the current Team to 0
        if curTeam == teamCount: curTeam = 0
        #The two lines above, can be written as curTeam = (curTeam + 1) % teamCount

    return teams

或者你使用 python 的生成器(这是 python 的强项):

makeTeams = lambda people, teamCount: [ [person for i, person in enumerate (people) if i % teamCount == team] for team in range (teamCount) ]
于 2012-12-11T01:59:20.230 回答