Python数据结构篇(二)

数据结构

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

列表

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

特点

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

优点

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

缺点

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

使用场景

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

创建列表

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

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

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

修改元素

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

添加元素

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

删除元素

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

列表操作

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

列表切片

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

# 基本使用
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。
# 基本使用
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 参数接受一个函数,该函数用于生成每个元素的比较键。
# 根据字符串的最后一个字母进行排序
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']
列表推导式

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

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

可以添加条件来过滤元素

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

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

# 创建一个学生成绩列表
student_grades = [85, 92, 78, 90, 88]
print("初始成绩:", student_grades)
# 访问第一个学生的成绩
first_grade = student_grades[0]
print("第一个学生的成绩:", first_grade)

# 访问最后一个学生的成绩
last_grade = student_grades[-1]
print("最后一个学生的成绩:", last_grade)
# 将第二个学生的成绩更新为95
student_grades[1] = 95
print("更新后的成绩:", student_grades)
# 添加一个新的学生成绩
student_grades.append(87)
print("添加新成绩后的列表:", student_grades)

# 在特定位置插入一个新的学生成绩
student_grades.insert(2, 89)
print("插入成绩后的列表:", student_grades)
# 删除特定的成绩
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)
# 获取前三个学生的成绩
top_three_grades = student_grades[:3]
print("前三个学生的成绩:", top_three_grades)

# 获取从第二个学生到最后的成绩
remaining_grades = student_grades[1:]
print("第二个学生到最后的成绩:", remaining_grades)
# 合并两个成绩列表
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)
# 创建一个所有成绩增加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)

元组

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

特点

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

优点

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

缺点

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

使用场景

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

创建元组

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

访问元素

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

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

# 原元组
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 中一种方便的语法特性,用于将元组(或其他可迭代对象)的元素赋值给多个变量,可以理解为创建多个变量

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

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

# 创建学生信息元组
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')
# 访问第一个学生的信息
name1 = student1[0]
age1 = student1[1]
major1 = student1[2]

print(f"Name: {name1}, Age: {age1}, Major: {major1}")
# 输出: Name: Alice, Age: 20, Major: Computer Science
# 解包学生信息
name2, age2, major2 = student2
print(f"Name: {name2}, Age: {age2}, Major: {major2}")
# 输出: Name: Bob, Age: 22, Major: Mathematics
# 遍历第一个学生的信息
for info in student1:
    print(info)

# 输出:
# Alice
# 20
# Computer Science
# 创建包含多个学生信息的嵌套元组
students = (student1, student2, student3)

# 打印嵌套元组
print(students)
# 输出: (('Alice', 20, 'Computer Science'), ('Bob', 22, 'Mathematics'), ('Charlie', 19, 'Physics'))
# 解包嵌套元组
(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),效率很高。
  • 灵活:支持动态添加和删除键值对。

缺点

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

使用场景

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

创建字典

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

访问和修改值

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

添加和删除键值对

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

字典操作

keys = phonebook.keys()  # 获取所有键
values = phonebook.values()  # 获取所有值
items = phonebook.items()  # 获取所有键值对
  • 字典排序
    • 按键排序:使用 sorted() 函数对字典的键进行排序,返回排序后的键列表或排序后的字典。
# 定义一个字典
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 参数对字典的值进行排序,返回排序后的键值对列表或排序后的字典。
# 定义一个字典
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 参数,可以按键或值进行降序排序。

键降序排序

# 定义一个字典
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}

按值降序排序

# 定义一个字典
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}
字典推导式

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

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

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

# 创建学生成绩字典
student_scores = {
    "Alice": 85,
    "Bob": 92,
    "Charlie": 78
}

# 打印字典
print(student_scores)  # 输出: {'Alice': 85, 'Bob': 92, 'Charlie': 78}
# 访问某个学生的成绩
alice_score = student_scores["Alice"]
print(f"Alice's score: {alice_score}")  # 输出: Alice's score: 85
# 修改某个学生的成绩
student_scores["Alice"] = 90
print(f"Alice's new score: {student_scores['Alice']}")  # 输出: Alice's new score: 90
# 添加新学生的成绩
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}
# 遍历字典的键
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
# 使用 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等。
集合的创建与操作

创建集合

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

添加和删除元素

number_set.add(6)
number_set.remove(3)

集合操作

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

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

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

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

# 学生选修的课程集合
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)
# 添加课程
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)
# 计算课程的并集
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)
# 遍历集合
print("Alice's courses:")
for course in alice_courses:
    print(course)

下一篇控制结构

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python数据结构包括列表、元组、字典、集合和字符串。列表是一种有序的可变容器,可以存储任意类型的数据。元组是一种有序的不可变容器,也可以存储任意类型的数据。字典是一种无序的键值对容器,可以通过键来访问值。集合是一种无序的唯一元素容器,可以进行集合运算。字符串是一种有序的不可变容器,用于存储文本数据。这些数据结构Python中非常常用,可以用于不同的数据处理操作。\[2\]\[3\] #### 引用[.reference_title] - *1* [python 数据结构](https://blog.csdn.net/qq_62047219/article/details/125618390)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Python语言的数据结构](https://blog.csdn.net/lmbuhuiku/article/details/129786853)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Python数据结构](https://blog.csdn.net/zt_96123/article/details/86830092)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

huhy~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值