将列表拆分为相等的部分

时间:2012-12-11 01:49:41

标签: python

此外,

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

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']

有人可以解释一下我放的吗?在它上面,我能正确理解概念吗?

1 个答案:

答案 0 :(得分:0)

我不太确定你想要达到的目标,但也许这符合你的目的:

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

使用people数组和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是否在列表people的范围内,以确保在下一行people[team+i]中没有失败。

标有问号的第二行会将列表team+i中位置people的元素附加到相应团队的列表中。当我采用num_teams范围的步骤时,你进入第一个团队(索引0)第二个团队(第1个团队)(第1个团队),第1个团队(第1个团队,第2团队,第2团队,第2团队,第2个团队) )-th,(2num_teams + 1)-the等人,等等所有团队。

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

编辑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) ]