我有一个列表列表:
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 中有很好的解释
我是一名优秀的程序员,十分优秀!