文章目录
- 前言
- 一、列表的创建与访问
- 二、列表操作:增删改查
- [三、列表推导式(List Comprehension)](#三、列表推导式(List Comprehension))
- 四、列表排序与复制
- 五、二维列表(矩阵)操作
前言
本文主要介绍列表的创建与访问、列表操作:增删改查、列表推导式、列表排序与赋值以及二维列表操作等知识点。
一、列表的创建与访问
- 列表创建
python
python
# 1. 方括号创建(最常用)
empty_list = [] # 空列表
numbers = [1, 2, 3, 4, 5] # 整数列表
fruits = ["apple", "banana", "orange"] # 字符串列表
mixed = [1, "hello", 3.14, True] # 混合类型列表
# 2. list()函数创建
list_from_string = list("Python") # ['P', 'y', 't', 'h', 'o', 'n']
list_from_range = list(range(5)) # [0, 1, 2, 3, 4]
# 3. 嵌套列表(列表中的列表)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 4. 列表推导式(稍后详解)
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
- 列表访问
python
python
fruits = ["apple", "banana", "orange", "grape", "mango"]
# 1. 索引访问(与字符串相同)
print(fruits[0]) # "apple"(正向索引,0开始)
print(fruits[-1]) # "mango"(负向索引,-1是最后一个)
# 2. 切片访问(返回新列表)
print(fruits[1:3]) # ["banana", "orange"](索引1到2)
print(fruits[:2]) # ["apple", "banana"](从开始到索引1)
print(fruits[2:]) # ["orange", "grape", "mango"](索引2到最后)
print(fruits[::2]) # ["apple", "orange", "mango"](步长为2)
print(fruits[::-1]) # 反转列表
# 3. 嵌套列表访问
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[0]) # [1, 2, 3](第一行)
print(matrix[0][1]) # 2(第一行第二列)
二、列表操作:增删改查
- 增加元素
python
python
fruits = ["apple", "banana"]
# 1. append() - 末尾添加单个元素
fruits.append("orange") # ["apple", "banana", "orange"]
# 2. insert() - 指定位置插入
fruits.insert(1, "grape") # ["apple", "grape", "banana", "orange"]
# 3. extend() - 合并另一个列表
more_fruits = ["mango", "peach"]
fruits.extend(more_fruits) # ["apple", "grape", "banana", "orange", "mango", "peach"]
# 4. + 运算符(创建新列表)
new_list = fruits + ["cherry", "berry"]
# 5. * 运算符(重复)
doubled = fruits * 2 # 列表重复两次
- 删除元素
python
python
fruits = ["apple", "banana", "orange", "grape", "banana"]
# 1. remove() - 删除第一个匹配值
fruits.remove("banana") # 删除第一个"banana",剩下["apple", "orange", "grape", "banana"]
# 2. pop() - 删除指定索引元素并返回该元素
removed = fruits.pop(1) # 删除索引1的元素("orange"),removed = "orange"
# 3. pop() - 无参数时删除最后一个
last = fruits.pop() # 删除最后一个元素
# 4. del - 按索引或切片删除
del fruits[0] # 删除索引0的元素
del fruits[1:3] # 删除切片范围内的元素
# del fruits # 删除整个列表变量
# 5. clear() - 清空列表所有元素
fruits.clear() # fruits变为[]
# 注意:删除时要避免索引越界!
- 修改元素
python
python
fruits = ["apple", "banana", "orange"]
# 1. 直接赋值修改
fruits[1] = "grape" # ["apple", "grape", "orange"]
# 2. 切片批量修改
fruits[0:2] = ["cherry", "berry"] # ["cherry", "berry", "orange"]
# 3. 切片替换(新元素个数可不同)
fruits[1:2] = ["mango", "peach", "lemon"] # ["cherry", "mango", "peach", "lemon", "orange"]
- 查找元素
python
python
fruits = ["apple", "banana", "orange", "grape", "banana"]
# 1. in / not in 成员检查
print("apple" in fruits) # True
print("watermelon" not in fruits) # True
# 2. index() - 返回元素首次出现的索引
idx = fruits.index("banana") # 1
# fruits.index("watermelon") # ValueError: 元素不存在
# 3. count() - 统计元素出现次数
print(fruits.count("banana")) # 2
print(fruits.count("apple")) # 1
三、列表推导式(List Comprehension)
列表推导式提供了一种简洁、高效创建列表的方法。
- 基本语法
python
python
# 传统方式
squares = []
for x in range(10):
squares.append(x**2)
# 列表推导式(一行搞定)
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
- 带条件的列表推导式
python
python
# 只包含偶数的平方
even_squares = [x**2 for x in range(10) if x % 2 == 0] # [0, 4, 16, 36, 64]
# 多个条件
numbers = [x for x in range(20) if x % 2 == 0 if x % 3 == 0] # [0, 6, 12, 18]
# if-else表达式(条件放在前面)
labels = ["偶数" if x % 2 == 0 else "奇数" for x in range(5)] # ["偶数", "奇数", "偶数", "奇数", "偶数"]
- 嵌套循环
python
python
# 生成所有坐标点
points = [(x, y) for x in range(3) for y in range(2)]
# [(0,0), (0,1), (1,0), (1,1), (2,0), (2,1)]
# 等价于:
points = []
for x in range(3):
for y in range(2):
points.append((x, y))
- 实用示例
python
python
# 1. 转换数据类型
str_numbers = ["1", "2", "3", "4", "5"]
int_numbers = [int(x) for x in str_numbers] # [1, 2, 3, 4, 5]
# 2. 过滤数据
words = ["apple", "banana", "cherry", "date", "elderberry"]
long_words = [w for w in words if len(w) > 5] # ["banana", "cherry", "elderberry"]
# 3. 提取特定属性
students = [{"name": "Alice", "score": 85}, {"name": "Bob", "score": 92}]
names = [student["name"] for student in students] # ["Alice", "Bob"]
四、列表排序与复制
- 排序操作
python
python
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
# 1. sort() - 原地排序(修改原列表)
numbers.sort() # [1, 1, 2, 3, 4, 5, 6, 9]
print(numbers)
# 降序排序
numbers.sort(reverse=True) # [9, 6, 5, 4, 3, 2, 1, 1]
# 2. sorted() - 返回新排序列表(不修改原列表)
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers) # 新列表:[1, 1, 2, 3, 4, 5, 6, 9]
print(numbers) # 原列表不变:[3, 1, 4, 1, 5, 9, 2, 6]
# 3. 自定义排序
words = ["apple", "banana", "cherry", "date"]
words.sort(key=len) # 按字符串长度排序:["date", "apple", "banana", "cherry"]
# 复杂排序示例
students = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 92},
{"name": "Charlie", "score": 78}
]
students.sort(key=lambda x: x["score"], reverse=True) # 按分数降序排序
- 反转列表
python
python
numbers = [1, 2, 3, 4, 5]
# 1. reverse() - 原地反转
numbers.reverse() # [5, 4, 3, 2, 1]
# 2. reversed() - 返回反转迭代器(需转换为列表)
reversed_numbers = list(reversed(numbers)) # [1, 2, 3, 4, 5](如果numbers是[5,4,3,2,1])
# 3. 切片反转
numbers = [1, 2, 3, 4, 5]
reversed_slice = numbers[::-1] # [5, 4, 3, 2, 1]
- 列表复制
python
python
# 重要:理解深浅拷贝的区别!
original = [1, 2, [3, 4]]
# 1. 浅拷贝 - 只复制第一层
shallow_copy = original.copy() # 或 shallow_copy = original[:] 或 list(original)
shallow_copy[0] = 99 # 修改第一层,不影响原列表
shallow_copy[2][0] = 88 # 修改第二层,会影响原列表!
print(original) # [1, 2, [88, 4]] ← 被影响了!
print(shallow_copy) # [99, 2, [88, 4]]
# 2. 深拷贝 - 完全独立复制
import copy
original = [1, 2, [3, 4]]
deep_copy = copy.deepcopy(original)
deep_copy[2][0] = 88 # 修改任何层都不影响原列表
print(original) # [1, 2, [3, 4]] ← 不受影响
print(deep_copy) # [1, 2, [88, 4]]
五、二维列表(矩阵)操作
- 创建与访问
python
python
# 1. 直接创建
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# 2. 列表推导式创建
rows, cols = 3, 4
matrix = [[0 for _ in range(cols)] for _ in range(rows)]
# [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
# 注意:错误的方式(引用同一列表)
wrong_matrix = [[0] * cols] * rows # 所有行是同一个列表的引用!
# 3. 访问元素
print(matrix[0][1]) # 第0行第1列:2
print(matrix[2][2]) # 第2行第2列:9
# 4. 遍历二维列表
for i in range(len(matrix)): # 遍历行
for j in range(len(matrix[i])): # 遍历列
print(f"matrix[{i}][{j}] = {matrix[i][j]}")
- 常见矩阵操作
python
python
# 1. 转置矩阵
matrix = [[1, 2, 3], [4, 5, 6]]
transpose = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
# [[1, 4], [2, 5], [3, 6]]
# 2. 矩阵相加
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
result = [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
# [[6, 8], [10, 12]]
# 3. 查找最大值及其位置
matrix = [[3, 7, 1], [8, 2, 5], [4, 6, 9]]
max_value = matrix[0][0]
max_position = (0, 0)
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] > max_value:
max_value = matrix[i][j]
max_position = (i, j)
print(f"最大值:{max_value},位置:{max_position}")