Skip to content Skip to sidebar Skip to footer

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

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

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

Post a Comment for "Counting The Number Of Wins For Teams In A Nested List"