你如何在python中组合名字?

时间:2015-02-02 09:48:00

标签: python list sorting average

我有两个名单,一个用于名称,一个用于得分,其中一些名称是相同的,我只需要制作一个名称,并将所有与该名称一致的分数分成一个与之相符的分数。 但它运行太多次并且崩溃时出现此错误消息

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

但如果我缩短循环,它就不会起作用

这是我到目前为止所拥有的:

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)

1 个答案:

答案 0 :(得分:1)

看起来最好使用字典:

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)