题解 | 合并表记录

合并表记录

https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201

line_n = int(input())

dict_a = {}
for i in range(line_n):
    input_n = input().split(" ")
    key = input_n[0]
    value = input_n[1]
    if key in dict_a:
        dict_a[key] = int(dict_a[key])+int(value)
               
    else:
        dict_a[key] = value

# print(dict_a)
list_key = list(dict_a.keys())
# # 一定要加key=int,如果不加则按照ASCII码排序,得出的结果和预期是不一样的
# list_key.sort(key=int)
# for key in list_key:
#     print(f'{key} {dict_a[key]}')

# list_a = sorted(list_key,key=int)
# for key in list_a:
#     print(f'{key} {dict_a[key]}')

# print(tuple(list(dict_a.items())))
# dict_a.items():直接返回字典的键值对元组列表
# key=lambda x: int(x[0]):这是实现数值排序的核心:
# lambda x:x 代表 dict_a.items() 中的每一个键值对元组(例如 ('8', 120532));
# x[0]:获取元组中的第一个元素,即字典的 key(字符串类型,例如 '8');
# int(x[0]):将字符串 key 转换为整数,sorted() 会基于该整数进行大小比较排序;
# 该方式不会修改原字典 dict_a,仅对 dict_a.items() 返回的键值对进行排序并遍历输出。
for key,value in sorted(dict_a.items(),key=lambda x: int(x[0])):
    print(f"{key} {value}")


  #1 先将合并后的值放入字典
  #2 用dict.key()方法得到一个key的列表,再将key进行排序(注意字符串排序是按ASCII码,需要转换成int)
  #3 得到排序后的列表,再按照列表中key的顺序来依次取字典中对应的value

    


    

全部评论

相关推荐

狸猫换offer:神通广大的互联网
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务