Reputation: 1
I have two lists one for names and one for scores some of the names are the same and I need to make only one name and an average all the scores that go with that name into one score that goes with it. but it runs too many times and crashes with this error message
Traceback (most recent call last):
File "N:\.idlerc\tester.py", line 12, in <module>
while l[i+j]==currentname:
IndexError: list index out of range
but if i make the loop shorter it doesn't work either
Here's what i have so far:
l=['bob','bob','dan','dan','dan']
s=[2,4,4,8,7]
averagelist=[]
averagescores=[]
i=0
while i<len(l)-1:
currentname=l[i]
score=0
j=0
while l[i+j]==currentname:
score=score+s[i+j]
j=j+1
#print(currentname)
#print('j',j)
#print('i',i)
#print('scores',score)
averagelist.append(currentname)
averagescores.append(score/j)
i=i+j
#print('i',i)
print(averagelist)
print(averagescores)
Upvotes: 0
Views: 470
Reputation: 591
Looks like it's better to use dictionary for this:
l=['bob','bob','dan','dan','dan']
s=[2,4,4,8,7]
scores_per_person = {}
for i,name in enumerate(l): #assuming both lists are of the same length
scores_per_person.setdefault(name,[]).append(s[i])
for name,scores_list in scores_per_person.iteritems():
average_score = sum(scores_list)/float(len(scores_list))
print "The average for %s is %f"%(name,average_score)
Upvotes: 1