我已经编写了一些我正在尝试使用的代码,以便计算一支足球队赢了一场比赛的次数。匹配被放置在嵌套列表中,其中每个子列表分别包含两个团队的名称和他们的游戏分数。
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场比赛赢了两场比赛,巨人队打了3场比赛,赢了零场比赛,钢人队打了8场比赛,赢了一场比赛。
这是我的代码到目前为止,它没有给我一些匹配的正确结果。它也没有对计数求和,所以它只是附加了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)
我也不允许在我的代码中使用任何词典!!
答案 0 :(得分:1)
尝试以下方法:
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]]
>>>
答案 1 :(得分:1)
您可以使用Counter
模块中的collections
并使用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]]