Counting the number of wins for teams in a nested list

帅比萌擦擦* 提交于 2020-01-07 04:23:30

问题


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]]

I want the output to be like this:

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

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.

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]]

My code:

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!!


回答1:


Try the following:

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]]
>>> 



回答2:


You can use Counter from collections module and using list comprehension to have your desired result like this example:

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)

Output:

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


来源:https://stackoverflow.com/questions/43906140/counting-the-number-of-wins-for-teams-in-a-nested-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!