列表(List) #
列表是Python中最常用的数据结构,是一个有序、可变的序列。
一、创建列表 #
1.1 基本创建 #
python
# 空列表
empty = []
empty = list()
# 带元素
numbers = [1, 2, 3, 4, 5]
strings = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True, None]
# 嵌套列表
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
1.2 使用list()函数 #
python
# 从其他可迭代对象创建
list_from_string = list("hello") # ['h', 'e', 'l', 'l', 'o']
list_from_tuple = list((1, 2, 3)) # [1, 2, 3]
list_from_range = list(range(5)) # [0, 1, 2, 3, 4]
1.3 列表推导式 #
python
# 基本推导式
squares = [x ** 2 for x in range(5)]
# [0, 1, 4, 9, 16]
# 带条件
evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]
二、访问元素 #
2.1 索引访问 #
python
fruits = ["apple", "banana", "cherry", "date"]
# 正向索引
print(fruits[0]) # "apple"
print(fruits[2]) # "cherry"
# 反向索引
print(fruits[-1]) # "date"(最后一个)
print(fruits[-2]) # "cherry"(倒数第二个)
# 索引越界
# print(fruits[10]) # IndexError
2.2 切片操作 #
python
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 基本切片
print(numbers[2:5]) # [2, 3, 4]
print(numbers[:3]) # [0, 1, 2]
print(numbers[7:]) # [7, 8, 9]
print(numbers[:]) # 复制整个列表
# 带步长
print(numbers[::2]) # [0, 2, 4, 6, 8](每隔一个)
print(numbers[1::2]) # [1, 3, 5, 7, 9](从索引1开始)
# 反向
print(numbers[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
print(numbers[8:2:-1]) # [8, 7, 6, 5, 4, 3]
# 负索引切片
print(numbers[-3:]) # [7, 8, 9]
print(numbers[:-3]) # [0, 1, 2, 3, 4, 5, 6]
三、修改列表 #
3.1 修改元素 #
python
fruits = ["apple", "banana", "cherry"]
# 修改单个元素
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry']
# 修改切片
fruits[1:3] = ["blackberry", "coconut"]
print(fruits) # ['apple', 'blackberry', 'coconut']
3.2 添加元素 #
python
fruits = ["apple", "banana"]
# append:末尾添加
fruits.append("cherry")
print(fruits) # ['apple', 'banana', 'cherry']
# insert:指定位置插入
fruits.insert(1, "blueberry")
print(fruits) # ['apple', 'blueberry', 'banana', 'cherry']
# extend:添加多个元素
fruits.extend(["date", "elderberry"])
print(fruits) # ['apple', 'blueberry', 'banana', 'cherry', 'date', 'elderberry']
# 使用 +=
fruits += ["fig", "grape"]
3.3 删除元素 #
python
fruits = ["apple", "banana", "cherry", "date", "banana"]
# del:按索引删除
del fruits[1]
print(fruits) # ['apple', 'cherry', 'date', 'banana']
# pop:弹出并返回
removed = fruits.pop() # 弹出最后一个
print(removed) # 'banana'
print(fruits) # ['apple', 'cherry', 'date']
removed = fruits.pop(1) # 弹出指定索引
print(removed) # 'cherry'
# remove:按值删除(只删除第一个)
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana")
print(fruits) # ['apple', 'cherry', 'banana']
# clear:清空列表
fruits.clear()
print(fruits) # []
四、列表方法 #
4.1 查找方法 #
python
fruits = ["apple", "banana", "cherry", "banana"]
# index:查找索引
print(fruits.index("cherry")) # 2
print(fruits.index("banana", 2)) # 3(从索引2开始查找)
# fruits.index("orange") # ValueError
# count:统计次数
print(fruits.count("banana")) # 2
print(fruits.count("orange")) # 0
# in:成员检查
print("apple" in fruits) # True
print("orange" in fruits) # False
4.2 排序方法 #
python
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# sort:原地排序
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
# 反向排序
numbers.sort(reverse=True)
print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
# 自定义排序键
words = ["apple", "pie", "banana", "cherry"]
words.sort(key=len)
print(words) # ['pie', 'apple', 'banana', 'cherry']
# sorted:返回新列表
numbers = [3, 1, 4, 1, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # [1, 1, 3, 4, 5]
print(numbers) # [3, 1, 4, 1, 5](原列表不变)
# reverse:原地反转
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers) # [5, 4, 3, 2, 1]
# reversed:返回迭代器
reversed_numbers = list(reversed(numbers))
4.3 其他方法 #
python
# copy:浅拷贝
original = [1, 2, 3]
copied = original.copy()
copied[0] = 10
print(original) # [1, 2, 3](不影响原列表)
# 复制的其他方式
copied = original[:]
copied = list(original)
# 浅拷贝的陷阱
original = [[1, 2], [3, 4]]
copied = original.copy()
copied[0][0] = 99
print(original) # [[99, 2], [3, 4]](嵌套列表受影响)
# 深拷贝
import copy
copied = copy.deepcopy(original)
五、列表运算 #
5.1 拼接 #
python
a = [1, 2, 3]
b = [4, 5, 6]
# 使用 +
c = a + b
print(c) # [1, 2, 3, 4, 5, 6]
# 使用 extend
a.extend(b)
# 使用 +=
a += b
5.2 重复 #
python
# 使用 *
zeros = [0] * 5
print(zeros) # [0, 0, 0, 0, 0]
# 注意嵌套
matrix = [[0] * 3] * 3 # 三行共享同一列表
matrix[0][0] = 1
print(matrix) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
# 正确方式
matrix = [[0] * 3 for _ in range(3)]
5.3 比较运算 #
python
# 相等比较
print([1, 2, 3] == [1, 2, 3]) # True
print([1, 2, 3] == [3, 2, 1]) # False
# 大小比较(字典序)
print([1, 2] < [1, 3]) # True
print([1, 2] < [1, 2, 3]) # True
六、遍历列表 #
6.1 基本遍历 #
python
fruits = ["apple", "banana", "cherry"]
# 遍历元素
for fruit in fruits:
print(fruit)
# 带索引遍历
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# 索引遍历
for i in range(len(fruits)):
print(fruits[i])
6.2 同时遍历多个列表 #
python
names = ["Tom", "Jerry", "Alice"]
ages = [25, 30, 28]
for name, age in zip(names, ages):
print(f"{name}: {age}岁")
6.3 遍历并修改 #
python
# 错误方式
# numbers = [1, 2, 3]
# for n in numbers:
# if n == 2:
# numbers.remove(n) # 可能出问题
# 正确方式1:遍历副本
numbers = [1, 2, 3, 4, 5]
for n in numbers[:]:
if n % 2 == 0:
numbers.remove(n)
# 正确方式2:列表推导式
numbers = [1, 2, 3, 4, 5]
numbers = [n for n in numbers if n % 2 != 0]
七、列表嵌套 #
7.1 访问嵌套元素 #
python
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0]) # [1, 2, 3]
print(matrix[0][1]) # 2
print(matrix[2][2]) # 9
7.2 展平嵌套列表 #
python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 方法1:列表推导式
flat = [x for row in matrix for x in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 方法2:itertools
import itertools
flat = list(itertools.chain.from_iterable(matrix))
# 方法3:sum
flat = sum(matrix, []) # 不推荐,效率低
7.3 转置矩阵 #
python
matrix = [[1, 2, 3], [4, 5, 6]]
# 使用zip
transposed = list(zip(*matrix))
print(transposed) # [(1, 4), (2, 5), (3, 6)]
# 列表推导式
transposed = [[row[i] for row in matrix] for i in range(3)]
八、列表作为栈和队列 #
8.1 栈(后进先出) #
python
stack = []
# 入栈
stack.append(1)
stack.append(2)
stack.append(3)
print(stack) # [1, 2, 3]
# 出栈
print(stack.pop()) # 3
print(stack.pop()) # 2
print(stack) # [1]
8.2 队列(先进先出) #
python
from collections import deque
queue = deque()
# 入队
queue.append(1)
queue.append(2)
queue.append(3)
print(queue) # deque([1, 2, 3])
# 出队
print(queue.popleft()) # 1
print(queue.popleft()) # 2
print(queue) # deque([3])
# 使用列表(效率较低)
queue = [1, 2, 3]
queue.pop(0) # 从头部删除,效率低
九、总结 #
| 操作 | 方法 | 示例 |
|---|---|---|
| 创建 | [], list() |
[1, 2, 3] |
| 访问 | 索引 | lst[0], lst[-1] |
| 切片 | [start:end:step] |
lst[1:3] |
| 添加 | append(), insert() |
lst.append(1) |
| 删除 | pop(), remove(), del |
lst.pop() |
| 查找 | index(), count() |
lst.index(1) |
| 排序 | sort(), sorted() |
lst.sort() |
| 反转 | reverse() |
lst.reverse() |
特点:
- 有序:元素有固定顺序
- 可变:可以修改元素
- 允许重复:可以有相同元素
- 异构:可以存储不同类型
最后更新:2026-03-16