题目
描述
数据表记录包含表索引和数值(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。
输入描述:
先输入键值对的个数
然后输入成对的index和value值,以空格隔开
输出描述:
输出合并后的键值对(多行)
示例1
输入:
4
0 1
0 2
1 2
3 4
输出:
0 3
1 2
3 4
解题思路
(1)记录输入的key, value个数,赋值给num
(2)新建空字典data_dict
(3)循环num次,用split分割输入的带空格的字符串,并赋值给临时变量key和value
(4)判断key是否已在data_dict中,在的话两个value求和,不在的话赋值value
(5)通过sorted函数对data_dict进行排序,key = lambda x:int(x[0])控制排序key
(6)逐步输出排序后的key和value
扩展:
(1)加入参数reverse可以进行倒排
(2)int函数用于将字符串转换成整数,否则排序会按照字符串排
>>>"3 4".split()
['3', '4']
>>>data_dict = {"1": 2, "3": 4}
>>>"1" in data_dict
True
>>>"5" in data_dict:
False
>>>"1" in data_dict.keys()
True
>>>sorted(data_dict.items(), key = lambda x:int(x[0]))
[('1', 2), ('3', 4)]
>>>sorted(data_dict.items(), key = lambda x:int(x[0]), reverse = True)
[('3', 4), ('1', 2)]
>>>data_dict = {"1": 2, "3": 4, "11": 4}
>>>sorted(data_dict.items(), key = lambda x:x[0])
[('1', 2), ('11', 4), ('3', 4)]
代码
while True:
try:
num = int(input())
data_dict = {}
for i in range(num):
key, value = input().split()
if key in data_dict:
data_dict[key] = data_dict[key] + int(value)
else:
data_dict[key] = int(value)
data = sorted(data_dict.items(), key = lambda x:int(x[0]))
for (key,value) in data:
print(str(key)+" "+str(value))
except Exception as e:
break