在 Python 中,列表(List)是一种有序、可变的数据结构,用于存储多个元素。列表中的元素可以是不同类型的数据,例如整数、字符串、浮点数,甚至是其他列表。列表是 Python 中最常用的数据结构之一。
1. 创建列表
列表用方括号 []
表示,元素之间用逗号 ,
分隔。
# 创建一个空列表
empty_list = []
# 创建一个包含多个元素的列表
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed_list = [1, "hello", 3.14, True]
2. 访问列表元素
列表中的元素可以通过索引访问,索引从 0
开始。负数索引表示从列表末尾开始计数。
fruits = ["apple", "banana", "cherry"]
# 访问第一个元素
print(fruits[0]) # 输出: apple
# 访问最后一个元素
print(fruits[-1]) # 输出: cherry
3. 修改列表元素
列表是可变的,可以通过索引修改元素。
fruits = ["apple", "banana", "cherry"]
# 修改第二个元素
fruits[1] = "blueberry"
print(fruits) # 输出: ['apple', 'blueberry', 'cherry']
4. 列表切片
切片操作可以获取列表的子集。语法为 list[start:end:step]
,其中 start
是起始索引,end
是结束索引(不包含),step
是步长。
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 获取前三个元素
print(numbers[:3]) # 输出: [0, 1, 2]
# 获取索引 2 到 5 的元素
print(numbers[2:6]) # 输出: [2, 3, 4, 5]
# 获取偶数索引的元素
print(numbers[::2]) # 输出: [0, 2, 4, 6, 8]
5. 列表操作
添加元素
append()
:在列表末尾添加一个元素。extend()
:在列表末尾添加多个元素。insert()
:在指定位置插入一个元素。
fruits = ["apple", "banana"]
# 添加一个元素
fruits.append("cherry")
print(fruits) # 输出: ['apple', 'banana', 'cherry']
# 添加多个元素
fruits.extend(["orange", "grape"])
print(fruits) # 输出: ['apple', 'banana', 'cherry', 'orange', 'grape']
# 在指定位置插入元素
fruits.insert(1, "blueberry")
print(fruits) # 输出: ['apple', 'blueberry', 'banana', 'cherry', 'orange', 'grape']
删除元素
remove()
:删除第一个匹配的元素。pop()
:删除指定位置的元素(默认删除最后一个元素)。del
:删除指定位置的元素或整个列表。
fruits = ["apple", "banana", "cherry", "banana"]
# 删除第一个匹配的元素
fruits.remove("banana")
print(fruits) # 输出: ['apple', 'cherry', 'banana']
# 删除指定位置的元素
fruits.pop(1)
print(fruits) # 输出: ['apple', 'banana']
# 删除整个列表
del fruits
其他操作
index()
:返回指定元素的索引。count()
:返回指定元素在列表中出现的次数。sort()
:对列表进行排序。reverse()
:反转列表中的元素。
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
# 查找元素的索引
print(numbers.index(5)) # 输出: 4
# 统计元素出现的次数
print(numbers.count(1)) # 输出: 2
# 排序
numbers.sort()
print(numbers) # 输出: [1, 1, 2, 3, 4, 5, 5, 6, 9]
# 反转
numbers.reverse()
print(numbers) # 输出: [9, 6, 5, 5, 4, 3, 2, 1, 1]
6. 列表推导式
列表推导式是一种简洁的创建列表的方式。
# 创建一个包含 0 到 9 的平方的列表
squares = [x**2 for x in range(10)]
print(squares) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
7. 嵌套列表
列表中的元素也可以是列表,形成嵌套列表。
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 访问嵌套列表中的元素
print(matrix[1][2]) # 输出: 6
8. 列表的复制
列表的复制需要注意浅拷贝和深拷贝的区别。
# 浅拷贝
original = [1, 2, 3]
copy = original.copy()
copy[0] = 99
print(original) # 输出: [1, 2, 3]
print(copy) # 输出: [99, 2, 3]
# 深拷贝(适用于嵌套列表)
import copy
original = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(original)
deep_copy[0][0] = 99
print(original) # 输出: [[1, 2], [3, 4]]
print(deep_copy) # 输出: [[99, 2], [3, 4]]
总结
Python 列表是一种非常灵活和强大的数据结构,适用于各种场景。掌握列表的基本操作和常用方法,可以大大提高编程效率。