欢迎访问宙启技术站
智能推送

使用Python编写的五个常用的数据结构案例

发布时间:2023-12-04 19:27:52

1. 列表(List)

列表是Python中最常用的数据结构之一,它用于存储多个元素,并且可以根据索引值访问和修改元素。列表使用方括号([])表示,并且可以包含任意类型的元素。

使用例子:

# 创建一个列表
fruits = ["apple", "banana", "cherry"]

# 访问列表元素
print(fruits[0])  # 输出: "apple"

# 修改列表元素
fruits[1] = "orange"
print(fruits)  # 输出: ["apple", "orange", "cherry"]

# 添加元素到列表末尾
fruits.append("grape")
print(fruits)  # 输出: ["apple", "orange", "cherry", "grape"]

# 删除列表中的元素
fruits.remove("orange")
print(fruits)  # 输出: ["apple", "cherry", "grape"]

2. 元组(Tuple)

元组是与列表类似的数据结构,不同之处在于元组的元素是不可变的,即不能修改和删除元素。元组使用圆括号(())表示,并且可以包含任意类型的元素。

使用例子:

# 创建一个元组
person = ("John", 25, "USA")

# 访问元组元素
print(person[0])  # 输出: "John"

# 尝试修改元组元素(报错)
person[1] = 30

# 元组解包
name, age, country = person
print(name, age, country)  # 输出: "John", 25, "USA"

3. 字典(Dictionary)

字典是一种无序的数据结构,用于存储键值对(key-value)映射关系的数据。字典使用花括号({})表示,每个键值对之间使用冒号(:)分隔。

使用例子:

# 创建一个字典
student = {"name": "John", "age": 20, "country": "USA"}

# 访问字典元素
print(student["name"])  # 输出: "John"

# 修改字典元素
student["age"] = 22
print(student)  # 输出: {"name": "John", "age": 22, "country": "USA"}

# 添加新的键值对
student["grade"] = "A"
print(student)  # 输出: {"name": "John", "age": 22, "country": "USA", "grade": "A"}

# 删除字典中的键值对
del student["country"]
print(student)  # 输出: {"name": "John", "age": 22, "grade": "A"}

4. 集合(Set)

集合是一种无序且不重复的数据结构,用于存储多个元素。集合使用花括号({})表示,每个元素之间使用逗号(,)分隔。

使用例子:

# 创建一个集合
fruits = {"apple", "banana", "cherry"}

# 判断元素是否在集合中
print("apple" in fruits)  # 输出: True

# 添加元素到集合
fruits.add("grape")
print(fruits)  # 输出: {"apple", "banana", "cherry", "grape"}

# 从集合中移除元素
fruits.remove("banana")
print(fruits)  # 输出: {"apple", "cherry", "grape"}

5. 栈(Stack)

栈是一种后进先出(Last-In-First-Out, LIFO)的数据结构,类似于一堆盘子叠放。栈有两个基本操作:入栈(push)和出栈(pop)。

使用例子:

# 创建一个栈
stack = []

# 入栈操作
stack.append("apple")
stack.append("banana")
stack.append("cherry")

# 出栈操作
print(stack.pop())  # 输出: "cherry"
print(stack.pop())  # 输出: "banana"
print(stack.pop())  # 输出: "apple"