用嵌套lis计算足球队赢了多少次

2024-06-25 23:35:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个函数来查看一个嵌套列表,其中包含两个团队和他们的游戏分数。这个列表包含多个匹配项,我希望输出是一个嵌套的列表,其中包含所有的球队名称和他们赢了多少场比赛。列表如下所示:

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)

Tags: 函数名称游戏元素列表count团队分数
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],它将为您提供零。你知道吗

您可以使用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转换为列表。。。你知道吗

或者,您可以使用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表达式变量。你知道吗

相关问题 更多 >