我有一个清单清单:

playoffTeamList = [[adSeed1, adSeed4], [adSeed2, adSeed3],
                   [mdSeed1, mdSeed4], (mdSeed2, mdSeed3],
                   [cdSeed1, cdSeed4], (cdSeed2, cdSeed3],
                   [pdSeed1, pdSeed4], (pdSeed2, pdSeed3]]


这是进入季后赛的运动队列表(即NHL或NBA风格的季后赛形式,最好是7轮)。列表中的每个列表都是将在第一轮对峙的成对团队。将有4个回合加冕冠军。

我想做的是从每对中输掉输掉的球队,并重新排列较大的名单,以便在迭代过程中将获胜者重新分列(或重新列出),以便下一轮看起来像:

playoffTeamList = [[adSeed1, adSeed2],
                   [mdSeed1, mdSeed2],
                   [cdSeed1, cdSeed2],
                   [pdSeed1, pdSeed2]]


下一轮:

playoffTeamList = [[adSeed1, mdSeed1],
                   [cdSeed1, pdSeed2]]


然后

playoffTeamList = [[adSeed1, pdSeed2]]


我的想法是从每个名单中删除失败的团队:

for brackets in playoffTeamList:
    playoffScoring() # This is an algorithm that plays each game of each best of seven round and returns a winner and/or loser
    brackets.remove(brackets[0])

print playoffTeamList


我只是想不通如何重新安排较大的名单,以使获胜的团队保留并重新安置。压缩或拉开拉链似乎无法将我带到那里。也许我只是缺少允许我执行此操作的方法或函数。

另外,我对其他有关如何设置清单的想法也持开放态度,这样可以更优雅地返回每一轮的优胜者并重新安排下一轮的比赛。也许是字典?也许还有别的吗?

最佳答案

def playoffScoring(team1, team2):
    return team1  # replace with actual scoring function

def games_round(games):
    winners = []
    for team1, team2 in games:
        winning_team = playoffScoring(team1, team2)
        winners.append(winning_team)

    return winners

def plan_games(teams):
    return zip(teams[::2], teams[1::2])

teams = [1, 2, 3, 4, 5, 6, 7, 8]
round = 0
while len(teams) > 1:
     round += 1
     print "Round {}: teams: {}".format(round, teams)
     games = plan_games(teams)
     teams = games_round(games)

champion = teams[0]  # only one left
print "Champion is {}".format(champion)


神奇之处在于plan_games函数-zip接受两个可迭代对象并将它们按元素逐个顺序连接。 [::2][1::2]是列表切片-在其他SO question中有很好的解释

关于python - 使用Python淘汰季后赛中的球队,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34273380/

10-10 00:20