【问题标题】:Counting how many times football teams have won using a nested list使用嵌套列表计算足球队获胜的次数
【发布时间】:2017-10-09 20:35:00
【问题描述】:

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

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}
  • 我还没有学会如何使用字典,所以我不知道该怎么做。
  • 记住 Tim Peters 的 Python 之禅扁平比嵌套更好。。因此,请使用字典而不是嵌套列表。

标签: python list count nested


【解决方案1】:

您可以使用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 转换为列表...

【讨论】:

  • 我可能应该说我还没有学会如何使用字典,所以我不会使用它们。
【解决方案2】:

您可以使用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 是的。但是这个 defaultdict 的默认值是 0,所以永远不会赢的球队总是有 0 作为值。
  • 当然,但是如果您将结构传递给不知道所有团队名称的人,信息就会丢失......并且 OP 的列表确实包含所有团队。
  • @Julien 有道理。这取决于 OP 的实际用例。
  • 我可能应该说我还没有学会如何使用字典,所以我不会使用它们。
【解决方案3】:

或者,您可以使用Counter,它类似于dict:

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})

您也可以add (subtract and perform set operations with)其他专柜:

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})

更新:另请参阅 this related answer 以获取 Counter/generator 表达式变体。

【讨论】:

    【解决方案4】:
    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}
    

    【讨论】:

      猜你喜欢
      • 2019-07-10
      • 1970-01-01
      • 2020-10-25
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 2016-09-18
      • 1970-01-01
      相关资源
      最近更新 更多