华为机考入门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 软件工程小施同学

相关推荐
千金裘换酒1 分钟前
LeetCode 数组经典题刷题
算法·leetcode·职场和发展
fie88891 小时前
MATLAB有限元框架程序
python·算法·matlab
小郭团队1 小时前
1_5_五段式SVPWM (传统算法反正切+DPWM1)算法理论与 MATLAB 实现详解
人工智能·嵌入式硬件·算法·dsp开发
思成Codes1 小时前
ACM训练:接雨水3.0——动态接雨水
数据结构·算法
alphaTao1 小时前
LeetCode 每日一题 2026/1/12-2026/1/18
python·算法·leetcode
sin_hielo1 小时前
leetcode 2943
数据结构·算法·leetcode
Snow_day.2 小时前
有关平衡树
数据结构·算法·贪心算法·动态规划·图论
Hcoco_me2 小时前
大模型面试题75:讲解一下GRPO的数据回放
人工智能·深度学习·算法·机器学习·vllm
Xの哲學2 小时前
Linux设备驱动模型深度解剖: 从设计哲学到实战演练
linux·服务器·网络·算法·边缘计算
明洞日记3 小时前
【CUDA手册002】CUDA 基础执行模型:写出第一个正确的 Kernel
c++·图像处理·算法·ai·图形渲染·gpu·cuda