白骑士的Python教学基础篇 1.5 数据结构

系列目录​​​​​​​

上一篇:白骑士的Python教学基础篇 1.4 函数与模块

数据结构是编程语言中用于存储和组织数据的基本构件。在Python中,常见的数据结构包括列表(List)、元组(Tuple)、字典(Dictionary)和集合(Set)。每种数据结构都有其独特的特性和用途。理解这些数据结构及其用法,对于编写高效且易于维护的Python代码至关重要。

列表(List)

列表是Python中最常用的数据结构之一。它是一个有序的集合,可以包含任意类型的元素,包括数字、字符串、其他列表等。列表是可变的,这意味着我们可以修改列表中的元素。

创建列表

python 复制代码
# 创建一个空列表
empty_list = []

# 创建一个包含元素的列表
fruits = ["apple", "banana", "cherry"]

访问列表元素

python 复制代码
# 通过索引访问元素
print(fruits[0])  # 输出: apple

# 通过负索引访问元素
print(fruits[-1])  # 输出: cherry

修改列表元素

python 复制代码
# 修改列表中的元素
fruits[1] = "blueberry"
print(fruits)  # 输出: ['apple', 'blueberry', 'cherry']

添加和删除元素

python 复制代码
# 使用append()方法添加元素
fruits.append("date")
print(fruits)  # 输出: ['apple', 'blueberry', 'cherry', 'date']

# 使用remove()方法删除元素
fruits.remove("blueberry")
print(fruits)  # 输出: ['apple', 'cherry', 'date']

# 使用pop()方法删除并返回最后一个元素
last_fruit = fruits.pop()
print(last_fruit)  # 输出: date
print(fruits)  # 输出: ['apple', 'cherry']

列表切片

python 复制代码
# 列表切片可以返回一个新的列表
print(fruits[0:2])  # 输出: ['apple', 'cherry']

列表推导式

python 复制代码
# 使用列表推导式创建列表
squares = [x**2 for x in range(10)]
print(squares)  # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

元组(Tuple)

元组与列表类似,但元组是不可变的。这意味着一旦创建,元组中的元素就不能修改。这使得元组适用于那些不希望被修改的数据集合。

创建元组

python 复制代码
# 创建一个空元组
empty_tuple = ()

# 创建一个包含元素的元组
numbers = (1, 2, 3)

访问元组元素

python 复制代码
# 通过索引访问元素
print(numbers[1])  # 输出: 2

# 通过负索引访问元素
print(numbers[-1])  # 输出: 3

不可变特性

python 复制代码
# 尝试修改元组中的元素会引发错误
# numbers[1] = 4  # 这行代码会引发TypeError

元组解包

python 复制代码
# 元组解包
a, b, c = numbers
print(a, b, c)  # 输出: 1 2 3

单元素元组

python 复制代码
# 创建一个包含单个元素的元组时需要在元素后加一个逗号
single_element_tuple = (4,)
print(single_element_tuple)  # 输出: (4,)

字典(Dictionary)

字典是Python中另一种重要的数据结构。它是一个无序的键值对集合,每个键必须是唯一的,可以是任意不可变数据类型,而值可以是任意数据类型。

创建字典

python 复制代码
# 创建一个空字典
empty_dict = {}

# 创建一个包含键值对的字典
person = {"name": "Alice", "age": 25, "city": "New York"}

访问字典元素

python 复制代码
# 通过键访问值
print(person["name"])  # 输出: Alice

# 使用get()方法访问值,如果键不存在则返回None
print(person.get("name"))  # 输出: Alice
print(person.get("address"))  # 输出: None

修改字典元素

python 复制代码
# 修改字典中的值
person["age"] = 26
print(person)  # 输出: {'name': 'Alice', 'age': 26, 'city': 'New York'}

# 添加新键值对
person["email"] = "alice@example.com"
print(person)  # 输出: {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@example.com'}

删除字典元素

python 复制代码
# 使用del关键字删除键值对
del person["city"]
print(person)  # 输出: {'name': 'Alice', 'age': 26, 'email': 'alice@example.com'}

# 使用pop()方法删除并返回指定键的值
email = person.pop("email")
print(email)  # 输出: alice@example.com
print(person)  # 输出: {'name': 'Alice', 'age': 26}

遍历字典

python 复制代码
# 遍历字典的键值对
for key, value in person.items():
    print(f"{key}: {value}")

# 输出:
# name: Alice
# age: 26

集合(Set)

集合是一个无序的不重复元素集合。集合主要用于成员关系测试和删除重复元素。集合支持数学上的集合操作,如并集、交集、差集等。

创建集合

python 复制代码
# 创建一个空集合
empty_set = set()

# 创建一个包含元素的集合
fruits_set = {"apple", "banana", "cherry"}

访问集合元素

python 复制代码
# 不能通过索引访问集合中的元素,但可以通过迭代访问
for fruit in fruits_set:
    print(fruit)

# 输出的顺序是无序的

添加和删除元素

python 复制代码
# 添加元素
fruits_set.add("date")
print(fruits_set)  # 输出: {'date', 'apple', 'cherry', 'banana'}

# 删除元素
fruits_set.remove("banana")
print(fruits_set)  # 输出: {'date', 'apple', 'cherry'}

# 使用discard()方法删除元素,如果元素不存在也不会引发错误
fruits_set.discard("banana")

集合操作

python 复制代码
# 创建两个集合
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

# 并集
union_set = set_a | set_b
print(union_set)  # 输出: {1, 2, 3, 4, 5, 6}

# 交集
intersection_set = set_a & set_b
print(intersection_set)  # 输出: {3, 4}

# 差集
difference_set = set_a - set_b
print(difference_set)  # 输出: {1, 2}

# 对称差集
symmetric_difference_set = set_a ^ set_b
print(symmetric_difference_set)  # 输出: {1, 2, 5, 6}

集合推导式

python 复制代码
# 使用集合推导式创建集合
squares_set = {x**2 for x in range(10)}
print(squares_set)  # 输出: {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

总结

Python提供了丰富的数据结构来处理不同类型的数据。列表(List)适用于有序且可变的集合;元组(Tuple)用于不可变的数据集合;字典(Dictionary)提供了键值对的映射;集合(Set)则用于处理无序且不重复的元素集合。通过理解和使用这些数据结构,可以编写出更高效、清晰且易维护的Python代码。无论是进行简单的数据存储,还是复杂的数据处理操作,这些数据结构都是不可或缺的工具。

下一篇:白骑士的Python教学进阶篇 2.1 面向对象编程(OOP)​​​​​​​

相关推荐
阿珊和她的猫2 小时前
v-scale-scree: 根据屏幕尺寸缩放内容
开发语言·前端·javascript
fouryears_234174 小时前
Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
开发语言·flutter·客户端·dart
我好喜欢你~5 小时前
C#---StopWatch类
开发语言·c#
lifallen6 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研6 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
wyiyiyi7 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
mit6.8247 小时前
[1Prompt1Story] 滑动窗口机制 | 图像生成管线 | VAE变分自编码器 | UNet去噪神经网络
人工智能·python
没有bug.的程序员7 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋7 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
cui__OaO8 小时前
Linux软件编程--线程
linux·开发语言·线程·互斥锁·死锁·信号量·嵌入式学习