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

相关推荐
freyazzr6 分钟前
Leetcode刷题 | Day60_图论06
数据结构·c++·算法·leetcode·图论
AI technophile14 分钟前
OpenCV计算机视觉实战(6)——经典计算机视觉算法
opencv·算法·计算机视觉
qq_5845989216 分钟前
day30python打卡
开发语言·人工智能·python·算法·机器学习
zhangpeng45554794018 分钟前
C++--综合应用-演讲比赛项目
开发语言·c++·算法
霜羽689228 分钟前
【数据结构篇】排序1(插入排序与选择排序)
数据结构·算法·排序算法
啊我不会诶30 分钟前
CF每日4题(1300-1400)
开发语言·c++·算法
JK0x0736 分钟前
代码随想录算法训练营 Day51 图论Ⅱ岛屿问题Ⅰ
算法·深度优先·图论
freyazzr40 分钟前
Leetcode刷题 | Day64_图论09_dijkstra算法
数据结构·c++·算法·leetcode·图论
珊瑚里的鱼1 小时前
【滑动窗口】LeetCode 1004题解 | 最大连续1的个数 Ⅲ
开发语言·c++·笔记·算法·leetcode
L_cl1 小时前
【Python 算法零基础 4.排序 ② 冒泡排序】
数据结构·python·算法