计算嵌套列表中球队的获胜次数 [英] Counting the number of wins for teams in a nested list
问题描述
我编写了一些代码,试图计算足球队赢得比赛的次数.将比赛放置在嵌套列表中,其中每个子列表分别包含两支球队的名称及其比赛得分.
I have written some code that I'm trying to use in order to calculate how many times a football team have won a match. The matches are placed into a nested list where each sub list contains the names of two teams and their scores for the game respectively.
L = [['Patriots', 'Giants', '3', '1'], ['Steelers', 'Patriots', '1', 2'], ['Giants', 'Steelers', '3', '5']]
但是,该列表更大,并且包含更多参加比赛的足球队.
However the list is much larger and contains more football teams who played in matches.
我已经有了一个最终列表,其中包含每个团队的名称以及他们参加的比赛次数,这些都是我成功计算出的.
I already have a final List which contains the name of each team and also the number of games they have played, which I calculated successfully.
finalList = [['Patriots', 7], ['Giants', 3], ['Steelers', 8]]
我希望输出像这样:
finalList = [['Patriots', 7, 2], ['Giants', 3, 0], ['Steelers', 8, 1]]
因为爱国者队打了7场比赛,赢得了两场比赛,巨人队打了3场,赢得了零场比赛,而钢人队打了8场,赢得了一场比赛.
because the Patriots played 7 games and won two games, Giants played 3 games and won zero games and Steelers played 8 games and won one game.
到目前为止,这是我的代码,对于某些比赛,它没有给我正确的结果.它也不会对计数求和,因此只附加一个数字1和0,如下所示:
This is my code so far, which doesn't give me the correct results for some of the matches. It also does not sum the counts so it just appends a number of 1's and 0's like this:
[['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)
我也不允许在我的代码中使用任何词典!
I am also not allowed to use any dictionaries in my code!!
推荐答案
尝试以下操作:
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]]
>>>
这篇关于计算嵌套列表中球队的获胜次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!