华为机考入门python3--(8)牛客8-合并表记录

分类:字典排序

知识点:

  1. 将输入转成int的列表 my_list = list(map(int, input().strip().split(' ')))

  2. 将列表转为元组 tuple(my_list)

  3. 访问元素为元组的列表 for first, second, third in my_list:

  4. 对字典进行排序 sorted(my_dict.items())

题目来自【牛客】

复制代码
n = int(input().strip())

# 假设数据表记录存储在列表中,每个元素是一个元组,包含索引和数值  
# records = [  (1, 10),  (2, 20),  (1, 30),  (3, 40),  (2, 50)]  
records = []
for i in range(n):
    # 转成int
    numbers = list(map(int, input().strip().split(' ')))
    records.append(tuple(numbers))

# print(records)

# 定义一个空字典用于存储合并后的键值对  
merged_dict = {}  

# 遍历数据表记录 ,(index,value)
for index, value in records:  
    # 如果索引已经在合并字典中,则将当前值累加到已有值上  
    if index in merged_dict:  
        merged_dict[index] += value  
    # 如果索引不在合并字典中,则将索引和值添加到字典中  
    else:  
        merged_dict[index] = value  

# print(merged_dict)
# 对合并后的键值对按照索引升序排序  
# 先转成列表dict_items([('name', 'John'), ('age', 30), ('city', 'New York')])
sorted_pairs = sorted(merged_dict.items())

# 输出合并后的键值对  
for index, value in sorted_pairs:
    print(f"{index} {value}")

by 软件工程小施同学

相关推荐
老师我太想进步了20261 小时前
【数据结构-8】栈的实现
c语言·数据结构·算法
kyle~2 小时前
因子图优化(Factor Graph Optimization)
c++·算法·机器人·传感器
Pniubi3 小时前
贪心算法入门
算法·贪心算法
MobotStone3 小时前
AI 能不能越用越会用?从“改答案”到“改进自己”,读懂 RSI
人工智能·算法
复杂网络与机器学习4 小时前
Meta 重写 K-Means:25 轮压成 2 轮,GPU 快 45 倍
人工智能·算法·数据挖掘
lunar_coder4 小时前
【算法】前缀和:把 O(n) 的重复劳动变成 O(1) 的一次查询
c++·算法
Pniubi4 小时前
力扣19 . 删除表的倒数第N个节点(栈)
算法·leetcode·职场和发展
青少儿编程课堂4 小时前
第十八届蓝桥杯青少组图形化 + 全国青少年信息素养大赛 + 电子学会图形化考级:校园三消乐大挑战解析
c++·python·算法·bfs·信息学竞赛
青少儿编程课堂5 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:网格连通块与岛屿数量(DFS+BFS双解)
c++·python·算法·bfs·信息学竞赛
forest_0916 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi