• l = int(input())
  • dic = {}
  • #idea:动态构建字典
  • for i in range(l):
  • line = input().split()
  • key = int(line[0])
  • value = int(line[1])
  • dic[key] = dic.get(key,0) + value #累积key对应的value值 #dic.get(key,0) 为什么要加0,是给了一个初始值吗
  • for each in sorted(dic): #最后的键值对按照升序排序 # sorted(dic) 直接就对字典进行了排序吗
    • print(each,dic[each])
  • 方案二更好理解
  • n = int(input())
  • temp = {}
  • for i in range(0,n):
  • s= input()
  • key = int(s.split(” “)[0])
  • value = int(s.split(” “)[1])
  • if key not in temp.keys():
  • temp[key] = value
  • else:
  • temp[key] = temp[key] + value
  • for key in sorted(temp): #python中sorted表示升序还是降序? sorted 对列表内的值按升序排列 reversed 对列表内的值按降序排列
  • print(key,temp[key])

作者 admin

张宴银,大数据开发工程师

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注