题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
#数据表记录包含表索引index和数值value(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照index值升序进行输出。 n = int(input()) #输入数据表个数 temp = {} #建立一个字典 for i in range(0, n): #range()生成一段左闭右开的整数范围 s =input() #input() 输入一串字符,以空格隔开 key = int(s.split(" ")[0]) #用split()将字符串分隔成列表 #空格为界,第一个值作为字典的关键字 value = int(s.split(" ")[1]) #用split()将字符串分隔成列表 #空格为界,第二个值作为字典的值 if key not in temp.keys(): #如果关键字不在字典里 temp[key] = value #则将关键字和值写入字典temp else: temp[key] = temp[key]+value #如果关键字在字典,则将值累加至之前 for key in sorted(temp): #调用sorted()函数,进行升序排序 #sorted函数是默认升序排序,当需要降序时,需要使用 reverse = True print(key, temp[key])