I’m working in python 2.7. I have a list of teams in the following dictionary:
NL = {'Phillies': [662, 476], 'Braves': [610, 550], 'Mets': [656, 687]}
The first value in the list is the amount of runs scored the team has, and the second is the amount of runs that team has given up.
I’m using this code to determine the Pythagorean winning percentage of each team, but I would also like to be able to have the function calculate the total number of runs scored and allowed by the group as a whole.
Right now I’m using:
Pythag(league):
for team, scores in league.iteritems():
runs_scored = float(scores[0])
runs_allowed = float(scores[1])
win_percentage = (runs_scored**2)/((runs_scored**2)+(runs_allowed**2))
total_runs_scored = sum(scores[0] for team in league)
print '%s: %f' % (team, win_percentage)
print '%s: %f' % ('League Total:', total_runs_scored)
I’m not sure exactly what is going on with the sum function, but instead of getting one value, I’m getting a different value over each iteration of the team and win_percentage, and it’s not the same value…
Ideally, the function would just return one value for the sum of the runs scored for each team in the dictionary.
Thanks for any help.
If you want to have the running total available, or don’t want to iterate over
leaguetwice, you can do:Remember that inside the loop you’re talking about a single team, so you don’t need to do a
sumto get the runs scored by that team, you instead need to add it to the runs scored by all the previous teams, that is, thescores[0]from the previous iterations of the loop.