【问题标题】:How do you group name's in python?你如何在python中对名称进行分组?
【发布时间】:2015-02-02 09:47:59
【问题描述】:

我有两个列表,一个用于名称,一个用于分数,其中一些名称是相同的,我只需要将一个名称和与该名称相关的所有分数平均为一个与之相关的分数。 但它运行了太多次并崩溃并显示此错误消息

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)

【问题讨论】:

  • l[i+j]==currentname的意图是什么? l[i]l[j] 都等于当前名称,或者索引 i 到 j 处的所有元素都等于当前名称?

标签: python list sorting average


【解决方案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)

【讨论】:

  • 您可以使用zip(l, s)避免冗余索引。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-23
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多