Python数据结构篇(二)

embedded/2024/9/24 10:24:56/

数据结构

    • 数据结构
      • 列表
        • 列表的创建与操作
        • 列表推导式
        • 案例实操
      • 元组
        • 案例实操
      • 字典
        • 字典的创建与操作
        • 字典推导式
        • 案例实操
      • 集合
        • 集合的创建与操作
        • 集合推导式
        • 案例实操

数据结构

Python 中常用的数据结构包括列表、元组、字典和集合。每种数据结构都有其独特的特性和使用场景

列表

列表是一种有序、可变的集合,可以包含任意类型的元素

特点

  • 有序:列表中的元素是有序的,可以通过索引访问。
  • 可变:可以修改列表中的元素,支持添加、删除、修改操作。
  • 允许重复:列表中可以包含重复的元素。

优点

  • 灵活性高:支持各种操作(增、删、改、查)。
  • 保持顺序:元素按插入顺序存储,适合需要顺序的场景。

缺点

  • 性能开销:对列表的操作(如插入和删除)可能会有性能开销,尤其是在列表较长时。
  • 内存占用:由于列表的灵活性,可能会占用更多的内存。

使用场景

  • 需要存储有序的元素并可能需要修改或扩展的场景,例如:学生名单、购物车等。
列表的创建与操作

创建列表

python">empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed = [1, "Hello", 3.14, True]

访问元素,需要注意列表中元素的位置表达,0表示第一个

python">numbers = [1, 2, 3, 4, 5]
print(numbers[0])  # 输出: 1
print(numbers[-1])  # 输出: 5

修改元素

python">numbers[0] = 10
print(numbers)  # 输出: [10, 2, 3, 4, 5]

添加元素

python">numbers.append(6)  # 添加到末尾
numbers.insert(0, 0)  # 插入到指定位置
print(numbers)  # 输出: [0, 10, 2, 3, 4, 5, 6]

删除元素

python">numbers.remove(10)  # 按值删除
last_element = numbers.pop()  # 删除并返回最后一个元素
first_element = numbers.pop(0)  # 删除并返回指定位置的元素
del numbers[0]  # 删除指定位置的元素

列表操作

python">concatenated = [1, 2] + [3, 4]  # 合并列表,会打印[1, 2, 3, 4]
repeated = [1, 2] * 3  # 重复列表,会打印[1, 2, 1, 2, 1, 2]

列表切片

python">nembers = [1,2,3,4,5,6,7]
subnet = nembers[1:3]  #获取子列表
print(subnet)  #打印[2,3],右不包含

列表排序;使用内置的 sort() 方法和 sorted() 函数

  • sort() 方法
    功能:对列表进行原地排序,修改列表本身,不返回新列表。
    语法:list.sort(key=None, reverse=False)

  • 数说明:
    key:指定一个函数,用于从每个列表元素中提取用于比较的键。如果不指定,则直接比较列表元素。
    reverse:如果为 True,则列表按降序排序。默认为 False

python"># 基本使用
numbers = [5, 2, 9, 1, 5, 6]
numbers.sort()
print(numbers)  # 输出: [1, 2, 5, 5, 6, 9]# 使用 reverse 参数
numbers.sort(reverse=True)
print(numbers)  # 输出: [9, 6, 5, 5, 2, 1]# 使用 key 参数
strings = ["banana", "apple", "cherry"]
strings.sort(key=len)
print(strings)  # 输出: ['apple', 'banana', 'cherry']
  • sorted() 函数
    功能:对列表进行排序,返回一个新列表,不修改原列表。
    语法:sorted(iterable, key=None, reverse=False)
  • 参数说明:
    iterable:要排序的可迭代对象(如列表)。
    key:指定一个函数,用于从每个列表元素中提取用于比较的键。如果不指定,则直接比较列表元素。
    reverse:如果为 True,则列表按降序排序。默认为 False。
python"># 基本使用
numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出: [1, 2, 5, 5, 6, 9]
print(numbers)  # 原列表不变: [5, 2, 9, 1, 5, 6]# 使用 reverse 参数
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc)  # 输出: [9, 6, 5, 5, 2, 1]# 使用 key 参数
strings = ["banana", "apple", "cherry"]
sorted_strings = sorted(strings, key=len)
print(sorted_strings)  # 输出: ['apple', 'banana', 'cherry']
  • 自定义排序
    无论是 sort() 方法还是 sorted() 函数,都可以通过 key 参数进行自定义排序。key 参数接受一个函数,该函数用于生成每个元素的比较键。
python"># 根据字符串的最后一个字母进行排序
def last_letter(s):return s[-1]strings = ["banana", "apple", "cherry"]
strings.sort(key=last_letter)
print(strings)  # 输出: ['banana', 'apple', 'cherry']# 使用 lambda 表达式
strings = ["banana", "apple", "cherry"]
sorted_strings = sorted(strings, key=lambda s: s[-1])
print(sorted_strings)  # 输出: ['banana', 'apple', 'cherry']
列表推导式

列表推导式是一种简洁的创建列表的方法,例如创建乘法口诀等等有规律的大量列表数据,这玩意考数学

python">squares = [x ** 2 for x in range(10)]  # 创建包含0到9的平方数的列表
print(squares)  # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

可以添加条件来过滤元素

python">even_squares = [x ** 2 for x in range(10) if x % 2 == 0]  # 仅包括偶数的平方
print(even_squares)  # 输出: [0, 4, 16, 36, 64]
案例实操

学生成绩管理系统;创建一个包含学生成绩的列表

python"># 创建一个学生成绩列表
student_grades = [85, 92, 78, 90, 88]
print("初始成绩:", student_grades)
python"># 访问第一个学生的成绩
first_grade = student_grades[0]
print("第一个学生的成绩:", first_grade)# 访问最后一个学生的成绩
last_grade = student_grades[-1]
print("最后一个学生的成绩:", last_grade)
python"># 将第二个学生的成绩更新为95
student_grades[1] = 95
print("更新后的成绩:", student_grades)
python"># 添加一个新的学生成绩
student_grades.append(87)
print("添加新成绩后的列表:", student_grades)# 在特定位置插入一个新的学生成绩
student_grades.insert(2, 89)
print("插入成绩后的列表:", student_grades)
python"># 删除特定的成绩
student_grades.remove(78)
print("删除特定成绩后的列表:", student_grades)# 删除并返回最后一个学生的成绩
last_removed = student_grades.pop()
print("删除最后一个成绩后的列表:", student_grades)
print("被删除的最后一个成绩:", last_removed)# 删除并返回指定位置的成绩
second_removed = student_grades.pop(1)
print("删除第二个位置成绩后的列表:", student_grades)
print("被删除的第二个成绩:", second_removed)# 删除特定位置的成绩
del student_grades[0]
print("删除第一个成绩后的列表:", student_grades)
python"># 获取前三个学生的成绩
top_three_grades = student_grades[:3]
print("前三个学生的成绩:", top_three_grades)# 获取从第二个学生到最后的成绩
remaining_grades = student_grades[1:]
print("第二个学生到最后的成绩:", remaining_grades)
python"># 合并两个成绩列表
more_grades = [75, 83]
all_grades = student_grades + more_grades
print("合并后的成绩列表:", all_grades)# 重复成绩列表
repeated_grades = student_grades * 2
print("重复的成绩列表:", repeated_grades)# 排序成绩列表
sorted_grades = sorted(student_grades)
print("排序后的成绩列表:", sorted_grades)# 原地排序
student_grades.sort()
print("原地排序后的成绩列表:", student_grades)
python"># 创建一个所有成绩增加5分的新列表
increased_grades = [grade + 5 for grade in student_grades]
print("增加5分后的成绩列表:", increased_grades)# 创建一个只包含及格成绩(>= 60)的新列表
passing_grades = [grade for grade in student_grades if grade >= 60]
print("及格的成绩列表:", passing_grades)

元组

元组是有序、不可变的集合。与列表类似,但不能修改

特点

  • 有序:元组中的元素是有序的,可以通过索引访问。
  • 不可变:一旦创建,元组中的元素不能修改,不支持添加或删除操作。
  • 允许重复:元组中可以包含重复的元素。

优点

  • 内存效率高:由于不可变性,元组在内存使用上比列表更高效。
  • 线程安全:不可变的特性使得元组在多线程环境中更安全。

缺点

  • 不灵活:不可变的特性意味着无法修改、添加或删除元素。

使用场景

  • 需要存储固定的数据集且不需要修改的场景,例如:函数的返回值、数据记录等。

创建元组

python">empty_tuple = ()
numbers = (1, 2, 3, 4, 5)
mixed = (1, "Hello", 3.14, True)
single_element_tuple = (1,)  # 注意逗号

访问元素

python">print(numbers[0])  # 输出: 1
print(numbers[-1])  # 输出: 5

排序;元组是不可变的序列,因此没有 sort() 方法。可以使用 sorted() 函数对元组进行排序,返回一个新的列表

python"># 原元组
numbers_tuple = (5, 2, 9, 1, 5, 6)# 使用 sorted() 函数排序
sorted_numbers = sorted(numbers_tuple)
print(sorted_numbers)  # 输出: [1, 2, 5, 5, 6, 9]# 使用 sorted() 函数和 reverse 参数
sorted_numbers_desc = sorted(numbers_tuple, reverse=True)
print(sorted_numbers_desc)  # 输出: [9, 6, 5, 5, 2, 1]

元组解包:是 Python 中一种方便的语法特性,用于将元组(或其他可迭代对象)的元素赋值给多个变量,可以理解为创建多个变量

python">a, b, c = (1, 2, 3)
print(a, b, c)  # 输出: 1 2 3
案例实操

有一组学生的信息,包括姓名、年龄和专业。我们将这些信息存储在一个元组中,并演示如何对这些元组进行各种操作

python"># 创建学生信息元组
student1 = ("Alice", 20, "Computer Science")
student2 = ("Bob", 22, "Mathematics")
student3 = ("Charlie", 19, "Physics")# 打印元组
print(student1)  # 输出: ('Alice', 20, 'Computer Science')
print(student2)  # 输出: ('Bob', 22, 'Mathematics')
print(student3)  # 输出: ('Charlie', 19, 'Physics')
python"># 访问第一个学生的信息
name1 = student1[0]
age1 = student1[1]
major1 = student1[2]print(f"Name: {name1}, Age: {age1}, Major: {major1}")
# 输出: Name: Alice, Age: 20, Major: Computer Science
python"># 解包学生信息
name2, age2, major2 = student2
print(f"Name: {name2}, Age: {age2}, Major: {major2}")
# 输出: Name: Bob, Age: 22, Major: Mathematics
python"># 遍历第一个学生的信息
for info in student1:print(info)# 输出:
# Alice
# 20
# Computer Science
python"># 创建包含多个学生信息的嵌套元组
students = (student1, student2, student3)# 打印嵌套元组
print(students)
# 输出: (('Alice', 20, 'Computer Science'), ('Bob', 22, 'Mathematics'), ('Charlie', 19, 'Physics'))
python"># 解包嵌套元组
(stud1, stud2, stud3) = students# 打印解包后的变量
print(stud1)  # 输出: ('Alice', 20, 'Computer Science')
print(stud2)  # 输出: ('Bob', 22, 'Mathematics')
print(stud3)  # 输出: ('Charlie', 19, 'Physics')

字典

字典是无序的键值对集合,键必须是唯一的且不可变,值可以是任意类型

特点

  • 无序(Python 3.7+ 保留插入顺序):字典中的键值对没有特定的顺序(但从 Python 3.7 开始,字典* 保持插入顺序)。
  • 可变:可以修改字典中的元素,支持添加、删除、修改操作。
  • 键唯一:字典中的每个键是唯一的,但值可以重复。

优点

  • 快速查找:通过键访问值的时间复杂度是 O(1),效率很高。
  • 灵活:支持动态添加和删除键值对。

缺点

  • 内存占用:由于存储键值对,字典可能占用更多内存。
  • 键要求可哈希:字典的键必须是不可变且可哈希的类型(如字符串、数字、元组等)。

使用场景

  • 需要通过唯一标识符(键)快速查找和存储数据的场景,例如:学生成绩记录、配置选项等。
字典的创建与操作

创建字典

python">empty_dict = {}
phonebook = {"Alice": "123-4567", "Bob": "987-6543"}

访问和修改值

python">print(phonebook["Alice"])  # 输出: 123-4567
phonebook["Alice"] = "111-2222"

添加和删除键值对

python">phonebook["Charlie"] = "555-0000"
del phonebook["Bob"]

字典操作

python">keys = phonebook.keys()  # 获取所有键
values = phonebook.values()  # 获取所有值
items = phonebook.items()  # 获取所有键值对
  • 字典排序
    • 按键排序:使用 sorted() 函数对字典的键进行排序,返回排序后的键列表或排序后的字典。
python"># 定义一个字典
student_scores = {"Charlie": 78, "Alice": 85, "Bob": 92}# 按键排序
sorted_keys = sorted(student_scores)
print(sorted_keys)  # 输出: ['Alice', 'Bob', 'Charlie']# 按键排序返回字典的键值对
sorted_dict_by_keys = {key: student_scores[key] for key in sorted_keys}
print(sorted_dict_by_keys)  # 输出: {'Alice': 85, 'Bob': 92, 'Charlie': 78}
  • 按值排序:使用 sorted() 函数和 key 参数对字典的值进行排序,返回排序后的键值对列表或排序后的字典。
python"># 定义一个字典
student_scores = {"Charlie": 78, "Alice": 85, "Bob": 92}# 按值排序
sorted_items_by_values = sorted(student_scores.items(), key=lambda item: item[1])
print(sorted_items_by_values)  # 输出: [('Charlie', 78), ('Alice', 85), ('Bob', 92)]# 按值排序返回字典
sorted_dict_by_values = {k: v for k, v in sorted_items_by_values}
print(sorted_dict_by_values)  # 输出: {'Charlie': 78, 'Alice': 85, 'Bob': 92}
  • 降序排序:通过设置 reverse=True 参数,可以按键或值进行降序排序。

键降序排序

python"># 定义一个字典
student_scores = {"Charlie": 78, "Alice": 85, "Bob": 92}# 按键降序排序
sorted_dict_by_keys_desc = {key: student_scores[key] for key in sorted(student_scores, reverse=True)}
print(sorted_dict_by_keys_desc)  # 输出: {'Charlie': 78, 'Bob': 92, 'Alice': 85}

按值降序排序

python"># 定义一个字典
student_scores = {"Charlie": 78, "Alice": 85, "Bob": 92}# 按值降序排序
sorted_items_by_values_desc = sorted(student_scores.items(), key=lambda item: item[1], reverse=True)
print(sorted_items_by_values_desc)  # 输出: [('Bob', 92), ('Alice', 85), ('Charlie', 78)]# 按值降序排序返回字典
sorted_dict_by_values_desc = {k: v for k, v in sorted_items_by_values_desc}
print(sorted_dict_by_values_desc)  # 输出: {'Bob': 92, 'Alice': 85, 'Charlie': 78}
字典推导式

字典推导式是一种简洁的创建字典的方法,和列表一样

python">squares = {x: x ** 2 for x in range(5)}  # 创建包含0到4的平方数的字典
print(squares)  # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
案例实操

有一组学生的成绩,我们将这些成绩存储在字典中,并演示如何对这些字典进行各种操作

python"># 创建学生成绩字典
student_scores = {"Alice": 85,"Bob": 92,"Charlie": 78
}# 打印字典
print(student_scores)  # 输出: {'Alice': 85, 'Bob': 92, 'Charlie': 78}
python"># 访问某个学生的成绩
alice_score = student_scores["Alice"]
print(f"Alice's score: {alice_score}")  # 输出: Alice's score: 85
python"># 修改某个学生的成绩
student_scores["Alice"] = 90
print(f"Alice's new score: {student_scores['Alice']}")  # 输出: Alice's new score: 90
python"># 添加新学生的成绩
student_scores["David"] = 88
print(student_scores)  # 输出: {'Alice': 90, 'Bob': 92, 'Charlie': 78, 'David': 88}# 删除某个学生的成绩
del student_scores["Charlie"]
print(student_scores)  # 输出: {'Alice': 90, 'Bob': 92, 'David': 88}
python"># 遍历字典的键
for student in student_scores:print(student)# 输出:
# Alice
# Bob
# David# 遍历字典的值
for score in student_scores.values():print(score)# 输出:
# 90
# 92
# 88# 遍历字典的键值对
for student, score in student_scores.items():print(f"{student}: {score}") #f 表示一种被称为“f-string”(格式化字符串字面值)的字符串格式化方法# 输出:
# Alice: 90
# Bob: 92
# David: 88
python"># 使用 get() 方法
alice_score = student_scores.get("Alice")
print(f"Alice's score: {alice_score}")  # 输出: Alice's score: 90# 获取所有键
students = student_scores.keys()
print(students)  # 输出: dict_keys(['Alice', 'Bob', 'David'])# 获取所有值
scores = student_scores.values()
print(scores)  # 输出: dict_values([90, 92, 88])# 获取所有键值对
items = student_scores.items()
print(items)  # 输出: dict_items([('Alice', 90), ('Bob', 92), ('David', 88)])

集合

集合是无序、不重复的元素集合

特点

  • 无序:集合中的元素是无序的,不支持索引。
  • 可变:可以修改集合,支持添加和删除操作,但元素本身必须是不可变类型。
  • 唯一:集合中的元素是唯一的,不允许重复。

优点

  • 去重功能:自动去除重复的元素。
  • 高效运算:支持集合运算(如并集、交集、差集),这些运算非常高效。

缺点

  • 无序:集合中的元素没有顺序,不支持索引访问。
  • 元素限制:集合中的元素必须是不可变类型(如字符串、数字、元组)。

使用场景

  • 需要处理唯一元素并执行集合运算的场景,例如:课程选修情况、唯一用户ID等。
集合的创建与操作

创建集合

python">empty_set = set()
number_set = {1, 2, 3, 4, 5}

添加和删除元素

python">number_set.add(6)
number_set.remove(3)

集合操作

python">a = {1, 2, 3}
b = {3, 4, 5}
union = a | b  # 并集
intersection = a & b  # 交集
difference = a - b  # 差集
symmetric_difference = a ^ b  # 对称差集
集合推导式

集合推导式是一种简洁的创建集合的方法

python">squares = {x ** 2 for x in range(5)}  # 创建包含0到4的平方数的集合
print(squares)  # 输出: {0, 1, 4, 9, 16}
案例实操

有一个学校系统,需要处理学生选修的课程。我们将使用集合来管理和操作这些课程

python"># 学生选修的课程集合
alice_courses = {"Math", "Physics", "Biology"}
bob_courses = {"History", "Math", "Biology"}
charlie_courses = {"Physics", "Chemistry", "Math"}# 打印集合
print("Alice's courses:", alice_courses)
print("Bob's courses:", bob_courses)
print("Charlie's courses:", charlie_courses)
python"># 添加课程
alice_courses.add("Computer Science")
print("Alice's updated courses:", alice_courses)# 删除课程
alice_courses.remove("Biology")  # 如果课程不存在,会抛出 KeyError
print("Alice's courses after removal:", alice_courses)# 使用 discard() 删除课程(不会抛出错误)
alice_courses.discard("Mathematics")  # 如果课程不存在,不会抛出错误
print("Alice's courses after discard:", alice_courses)
python"># 计算课程的并集
all_courses = alice_courses | bob_courses | charlie_courses
print("All courses offered:", all_courses)# 计算课程的交集
common_courses = alice_courses & bob_courses
print("Courses taken by both Alice and Bob:", common_courses)# 计算课程的差集
alice_only_courses = alice_courses - bob_courses
print("Courses only Alice is taking:", alice_only_courses)# 计算课程的对称差集
unique_courses = alice_courses ^ bob_courses
print("Courses taken by either Alice or Bob but not both:", unique_courses)
python"># 遍历集合
print("Alice's courses:")
for course in alice_courses:print(course)

下一篇控制结构


http://www.ppmy.cn/embedded/90785.html

相关文章

PHP反序列化漏洞从入门到深入8k图文介绍,以及phar伪协议的利用

文章参考:w肝了两天!PHP反序列化漏洞从入门到深入8k图文介绍,以及phar伪协议的利用 前言 本文内容主要分为三个部分:原理详解、漏洞练习和防御方法。这是一篇针对PHP反序列化入门者的手把手教学文章,特别适合刚接触PH…

Java中的5种线程池类型

Java中的5种线程池类型 1. CachedThreadPool (有缓冲的线程池)2. FixedThreadPool (固定大小的线程池)3. ScheduledThreadPool(计划线程池)4. SingleThreadExecutor (单线程线程池)…

三、Spring-WebFlux实战案例-流式

目录 一、springboot之间通讯方式 1. 服务端 (Spring Boot) 1.1 添加依赖 1.2 控制器 2. 客户端 (WebClient) 2.1 添加依赖 2.2 客户端代码 3. 运行 二、web与服务之间通讯方式 1、服务端代码 2、客户端代码 3、注意事项 三、移动端与服务端之间通讯方式…

Bug 解决 | 无法正常登录或获取不到用户信息

目录 1、跨域问题 2、后端代码问题 3、前端代码问题 我相信登录这个功能是很多人做项目时候遇到第一个槛! 看起来好像很简单的登录功能,实际上还是有点坑的,比如明明账号密码都填写正确了,为什么登录后请求接口又说我没登录&a…

我所理解的sprd-camera摄像头框架流程分析

摄像头的图像格式:RGB24,RGB565,RGB444,YUV4:2:2 RGB24 表示R、G、B ,3种基色都用8个二进制位表示,那么红色、绿色、蓝色各有256种,那么由这三种基色构成的颜色就是256X256X256=16,777,216种,约等于1677万。UV 和我们熟知的 RGB 类似,是一种颜色编码格式。 YUV 包含三…

“vcruntime140.dll找不到”的错误怎么处理?一键修复vcruntime140.dll

遇到“vcruntime140.dll找不到”的错误提示时,这通常指的是尝试运行需要Visual C 2015 Redistributable支持的软件时由于该文件的缺失而导致程序无法启动。这种情况在使用Windows操作系统的用户中并不少见。为了帮大家在将来遇到此类问题时能够迅速解决,…

概率论原理精解【9】

文章目录 集类拓扑空间基 参考文献 集类 C是一个集类(以G的某些子集为元素的集合称为G的集类)。 A i ∈ C , ∩ i 1 n A i ∈ C , 此为有限交封闭 C 所得集类 C ∩ f A_i \in C,\cap_{i1}^nA_i \in C,此为有限交封闭C所得集类C_{\cap f} Ai​∈C,∩i1n…

【Linux】网络基础_4

文章目录 十、网络基础5. socket编程网络翻译服务 未完待续 十、网络基础 5. socket编程 网络翻译服务 基于UDP&#xff0c;我们实现一个简单的翻译。 我们导入之前写的代码&#xff1a; InetAddr.hpp&#xff1a; #pragma once#include <iostream> #include <sys…