Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

python - Adding the sorted elements in list

I have a list ["Roll_Number","Marks in subjects"]:

list_1=[(1,22),(1,22),(2,29),(2,16),(3,56),(4,32),(4,12)]

I tried this code in python to get sum of all subjects for each roll_no :

 sub_sum = [0] * 4 #Roll No :4
 if i in range(0,len(list1)):
 if k in range(0,5):
    if (list1[i][0]==k):
       sub_sum[k] = list1[i][1] + sub_sum[k]
       i=i+1
    else:
        k=k+1
        break

Getting an infinite loop. Expected Result : 1:44 , 2:45, 3:56 , 4:44 Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do that as follows:

from collections import defaultdict

a = [(1,22),(1,22),(2,29),(2,16),(3,56),(4,32),(4,12)]

b = defaultdict(lambda: 0)
for i,j in a:
    b[i] += j

>>> print b
{1:44, 2:45, 3:56, 4:44}

DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...