Python数据结构篇(二)

数据结构

数据结构

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)

下一篇控制结构

相关推荐
databook1 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar3 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户8356290780513 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_3 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
数据智能老司机10 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机11 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机11 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机11 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i11 小时前
drf初步梳理
python·django
每日AI新事件11 小时前
python的异步函数
python