簡體   English   中英

您如何在python中對名稱進行分組?

[英]How do you group name's in python?

我有兩個列表,一個用於名稱,一個用於分數,其中一些名稱是相同的,我只需要命名一個名稱,然后將與該名稱相關的所有分數平均取為一個與之相關的分數。 但它運行太多次,並因該錯誤消息而崩潰

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=['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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM