题目描述
数据表记录包含表索引和数值(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。
输入描述:
先输入键值对的个数
然后输入成对的index和value值,以空格隔开
输出描述:
输出合并后的键值对(多行)
示例1
输入
复制
4
0 1
0 2
1 2
3 4
输出
复制
0 3
1 2
3 4
代码块
- 有序列表内容
- 有序列表内容
while True:
try:num=int(input()) index1=[] value1=[] hb_index={} hb_value=set() for i in range(num): a=list(map(int,input().split())) #输入处理为整数类型,采用list(map(int,input().split())) if a[0] not in hb_index : #双数组的处理,可以采用字典来实现,即判断不在新增的列表(字典)里,即判断增加 #关键index,以及增加dic(index)=value hb_value.add(a[0]) hb_index[a[0]]=a[1] else: hb_index[a[0]]= hb_index[a[0]]+a[1] result=sorted(hb_value,reverse=False) for index1 in result: print(index1,hb_index.get(index1)) #读取字典采用dic.get(index),可以获取index的value值
except:break