使用嵌套列表计算足球队赢得比赛的次数

3

我需要编写一个函数来查看一个包含两个团队和他们的比分的嵌套列表。该列表包含多场比赛,我希望输出为一个嵌套列表,显示所有团队的名称及其赢得的比赛数。该列表如下:

L = [['Patriots', 'Giants', '3', '1'], ['Steelers', 'Patriots', '1', 2'], ['Giants', 'Steelers', '3', '5']]

在上面的列表中,前两个元素是团队名称,第三个和第四个元素是他们在比赛中得分。然而,该列表比这个要大得多,有更多的团队。输出结果可能如下所示:

finalList = [['Patriots', 2], ['Giants', 0], ['Steelers', 1]]

因为爱国者赢了两场比赛,巨人队赢了零场比赛,钢人队赢了一场比赛。
我尝试过以下代码,但它不起作用,我被卡住了。
def gamesWon():
    for i in L:
        count = 0
        if i[2]>i[3]:
            count += 1
            i.append(count)

为什么不将finalList作为一个字典,以团队名称为键,得分为值:finalList = {'Patriots': 2, 'Giants': 0} - R. Gadeev
我还没有学会如何使用字典,所以我不知道该怎么做。 - Billy Whales
记住 Tim Peters 的 Python之禅:“扁平比嵌套更好。” 因此,使用字典而不是嵌套列表。 - R. Gadeev
4个回答

3
您可以使用一个 defaultdict:
from collections import defaultdict
# initialize the result as a defaultdict with default value of 0
result = defaultdict(lambda : 0)   

for t1,t2,s1,s2 in L:
    if int(s1) > int(s2):
        result[t1] += 1
    elif int(s2) > int(s1):
        result[t2] += 1

result
# defaultdict(<function __main__.<lambda>>, {'Patriots': 2, 'Steelers': 1})

请注意,尽管在结果中缺少得分为零的团队,但如果您调用result [team],它会给您返回零。这一点需要注意。

这不包括从未获胜的团队! - Julien
@Julien 这是真的。但是这个defaultdict的默认值是0,所以从来没有赢过的队伍将始终具有0作为值。 - Psidom
当然,但是如果你将该结构传递给不知道所有团队名称的人,信息就会丢失...而OP的列表包含所有团队。 - Julien
@Julien 说得有道理。这取决于OP的实际使用情况。 - Psidom
我应该明确一下,我还没有学会如何使用字典,所以我不能使用它们。 - Billy Whales
那就重新发明轮子吧:创建一个类似于字典的结构,下面带有列表...虽然这样做会很麻烦和低效,但它能够工作。你的问题正是构建一个字典! - Julien

2
您可以使用defaultdict
from collections import defaultdict

L = [['Patriots', 'Giants', '3', '1'], ['Steelers', 'Patriots', '1', '2'], ['Giants', 'Steelers', '3', '5']]

D = defaultdict(int)

for match in L:
    team1, team2, score1, score2 = match
    D[team1] # make sure the team exist in the dict even if it never wins a match
    D[team2] # make sure the team exist in the dict even if it never wins a match
    if int(score1) > int(score2):
        D[team1] += 1
    if int(score2) > int(score1):
        D[team2] += 1

如果您确实需要,您可以轻松地将 D 转换为列表...

我应该明确一下,我还没有学会如何使用字典,所以我不能使用它们。 - Billy Whales

0

或者,您可以使用类似字典的Counter

import collections as ct

L = [
    ['Patriots', 'Giants', '3', '1'], 
    ['Steelers', 'Patriots', '1', '2'], 
    ['Giants', 'Steelers', '3', '5'],
    ['Giants', 'Patriots', '1', '1']                       # tie  
]    

def count_wins(games):
    """Return a counter of team wins, given a list of games."""
    c = ct.Counter()                                        
    for team1, team2, s1, s2 in games:
        c[team1] += 0
        c[team2] += 0
        if int(s1) == int(s2):
            continue
        elif int(s1) > int(s2):
            c[team1] += 1
        else:
            c[team2] += 1
    return c

season = count_wins(L)
season
# Counter({'Giants': 0, 'Patriots': 2, 'Steelers': 1})

后面的代码为新条目提供了零增量的默认值,并处理平局:

L_tie = [['Cowboys', 'Packers', '3', '3']]
game = count_wins(L_tie)
game
# Counter({'Cowboys': 0, 'Packers': 0})

计数器具有一些有用的方法来查找顶级团队:
season.most_common(2)
# [('Patriots', 2), ('Steelers', 1)]

计数器很灵活。您可以轻松更新计数器:

season.update(game)
season
# Counter({'Cowboys': 0, 'Giants': 0, 'Packers': 0, 'Patriots': 2, 'Steelers': 1})

您还可以与其他计数器进行加(减)和集合操作

L_last = [['49ers', 'Raiders', '7', '10'], ['Packers', 'Patriots', '3', '7']] 
last_season = count_wins(L_last)
season + last_season
# Counter({'Patriots': 3, 'Raiders': 1, 'Steelers': 1})

更新:还可以参考这个相关答案,使用Counter/生成器表达式变体。


0
ll = [['Patriots', 'Giants', '3', '1'], ['Steelers', 'Patriots', '1', '2'], ['Giants', 'Steelers', '3', '5']]

teamStatus = {}

for l in ll:
  team1,team2,team1_score,team2_score = l
  if team1 not in teamStatus:
      teamStatus[team1] = 0
  if team2 not in teamStatus:    
      teamStatus[team2] = 0

  if int(team1_score) > int(team2_score):
    teamStatus[team1] += 1 
  else:
    teamStatus[team2] += 1

print(teamStatus)

结果

{'Patriots': 2, 'Giants': 0, 'Steelers': 1}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接