Counting the number of wins for teams in the nested list

I wrote the code that I am trying to use to calculate how many times a football team has won a match. The matches are placed in a nested list, where each additional list contains the names of the 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 that have played matches.

I already have a final list that contains the name of each team as well as the number of games they played that I calculated successfully.

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

      

I want the result to be like this:

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

      

because the Patriots played 7 games and won two games, the Giants played 3 games and won zero games, and the Steelers played 8 games and won one game.

This is my code so far, which is not giving me correct results for some matches. It also doesn't add the counters, so it just adds the number 1 and 0 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 dictionaries in my code!

0


source to share


2 answers


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

      

+1


source


You can use the module Counter

from collections

and using list comprehension

to get the desired output like in 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]]

      

+1


source







All Articles