在嵌套的lis中计算团队的获胜数

2024-06-25 23:38:59 发布

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

我写了一些代码,我试图用这些代码来计算一个足球队赢得一场比赛的次数。比赛被放入一个嵌套列表中,每个子列表分别包含两个队的名称和他们在比赛中的得分。在

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

然而,这份名单要大得多,其中包括了更多参加比赛的足球队。在

我已经有了一个最终的名单,其中包括每个队的名字,以及他们已经玩过的游戏的数量,我计算成功了。在

^{pr2}$

我希望输出是这样的:

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

因为爱国者队打了7场比赛,赢了2场,巨人队打了3场比赛,赢了0场,钢铁队打了8场比赛,赢了1场。在

到目前为止,这是我的代码,它没有给出一些匹配的正确结果。它也不求和计数,所以它只是附加一个数字1和0,如下所示:

[['Giants', 5, 1, 0, 1]]

我的代码:

for i in L:
    countLeft = 0
    countRight = 0
    if i[2]>i[3]:
        countLeft += 1
    elif i[3]>i[2]:
        countRight += 1
        for k in finalList:
            if i[0]==k[0]:
                k.append(countLeft)
            elif i[1]==k[0]:
                k.append(countRight)
print(finalList)

我也不允许在我的代码中使用任何字典!!在


Tags: 代码in列表forifelif名单append
2条回答

尝试以下操作:

for k in finalList:
    k.append(0)

for i in L:
    if int(i[2]) > int(i[3]):
            for k in finalList:
                    if k[0] == i[0]:
                            k[2]+=1
    elif int(i[3]) > int(i[2]):
            for k in finalList:
                    if k[0] == i[1]:
                            k[2]+=1

^{pr2}$

您可以使用来自collections模块的Counter,并使用list comprehension获得您想要的结果,如下例所示:

from collections import Counter

a = [['Patriots', 'Giants', '3', '1'], ['Steelers', 'Patriots', '1', '2'], ['Giants', 'Steelers', '3', '5']]
b = [['Patriots', 7], ['Giants', 3], ['Steelers', 8]]

wins = Counter(team1 if int(team1_s) > int(team2_s) else team2 if int(team2_s) > int(team1_s) else None for team1, team2, team1_s, team2_s in a)

final = final = [[k,l,c[k]] if k in wins else [k,l,0] for k,l in b]

print(final)

输出:

^{pr2}$

相关问题 更多 >