计算嵌套列表中团队的获胜次数



我写了一些代码,我试图用它来计算一支足球队赢得比赛的次数。比赛被放置在一个嵌套列表中,其中每个子列表分别包含两支球队的名称及其比赛得分。

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

然而,这个名单要大得多,并且包含更多参加比赛的足球队。

我已经有了一个最终列表,其中包含每支球队的名称以及他们参加的比赛数量,我成功计算了。

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

我希望输出是这样的:

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)

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

尝试以下操作:

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

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

您可以使用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)

输出:

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

最新更新