4. 数据结构
在 Python 中,数据结构是组织和存储数据的基本方式。常见的数据结构包括列表(List)、元组(Tuple)、字典(Dict)和集合(Set)。这些数据结构各有特点,适用于不同的应用场景。以下是关于列表和元组的详细介绍。
4.1 列表(List)
列表是 Python 中最常用的数据结构之一,它是一个有序、可变的集合,可以存储不同类型的元素。列表非常适合用于需要频繁修改和访问的数据集。
创建列表
创建列表非常简单,只需将元素放在方括号 [] 内即可。元素之间用逗号分隔。列表可以包含不同类型的数据,如整数、浮点数、字符串等。
# 创建一个简单的列表
numbers = [1, 2, 3, 4, 5]
print(numbers) # 输出: [1, 2, 3, 4, 5]
# 创建一个混合类型的列表
mixed_list = [1, "apple", 3.14, True]
print(mixed_list) # 输出: [1, 'apple', 3.14, True]
# 使用 list() 函数创建列表
empty_list = list()
print(empty_list) # 输出: []
# 使用列表推导式创建列表
squares = [x**2 for x in range(6)]
print(squares) # 输出: [0, 1, 4, 9, 16, 25]
访问列表元素
列表中的元素可以通过索引来访问,索引从0开始。你还可以使用负索引来从列表末尾开始访问元素。
# 访问列表中的单个元素
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # 输出: apple
print(fruits[1]) # 输出: banana
print(fruits[-1]) # 输出: cherry
# 访问列表中的多个元素(切片)
print(fruits[0:2]) # 输出: ['apple', 'banana']
print(fruits[:2]) # 输出: ['apple', 'banana']
print(fruits[1:]) # 输出: ['banana', 'cherry']
print(fruits[-2:]) # 输出: ['banana', 'cherry']
# 遍历列表中的所有元素
for fruit in fruits:
print(fruit)
# 输出:
# apple
# banana
# cherry
# 使用 enumerate() 函数获取索引和值
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
# 输出:
# Index 0: apple
# Index 1: banana
# Index 2: cherry