【Python 列表(List)】
Python 中的列表(List)是最常用、最灵活的有序数据集合,支持动态增删改查操作。以下是列表的核心知识点:
一、基础特性
- 有序性:元素按插入顺序存储
- 可变性:支持增删改操作
- 允许重复:可存储重复元素
- 异构性:可包含不同类型数据
my_list = [1, "apple", 3.14, True]
二、创建列表
1. 直接定义
fruits = ["apple", "banana", "orange"]
empty_list = [] # 空列表
2. 类型转换
list("hello") # → ['h', 'e', 'l', 'l', 'o']
list((1,2,3)) # → [1, 2, 3]
3. 快速初始化
zeros = [0] * 5 # → [0, 0, 0, 0, 0]
matrix = [[0]*3 for _ in range(3)] # 二维列表
三、常用操作
1. 索引与切片
nums = [10, 20, 30, 40, 50]
nums[0] # → 10(正向索引,从0开始)
nums[-1] # → 50(反向索引,从-1开始)
nums[1:4] # → [20, 30, 40](切片,左闭右开)
nums[::-1] # → [50, 40, 30, 20, 10](逆序)
2. 增删改查
# 增
nums.append(60) # 末尾添加 → [10,20,30,40,50,60]
nums.insert(2, 25) # 指定位置插入 → [10,20,25,30,40,50]# 删
nums.pop() # 删除末尾元素 → 返回60
nums.remove(30) # 删除第一个匹配项 → 删除30
del nums[1:3] # 删除索引1-2的元素 → 删除20,25# 改
nums[0] = 100 # 修改索引0的元素 → [100,40,50]# 查
if 50 in nums: # 成员检查 → Trueprint("存在")
四、常用方法
1. 排序与反转
nums = [3, 1, 4, 1, 5]
nums.sort() # 原地排序 → [1, 1, 3, 4, 5]
sorted_nums = sorted(nums) # 返回新列表 → [1,1,3,4,5]
nums.reverse() # 原地反转 → [5,4,3,1,1]
2. 统计与查找
nums.count(1) # 统计出现次数 → 2
nums.index(4) # 查找首次出现位置 → 2
3. 连接与复制
a = [1,2]
b = [3,4]
a + b # → [1,2,3,4](生成新列表)
a * 2 # → [1,2,1,2]
a.extend(b) # 原地扩展 → a变为[1,2,3,4]
五、嵌套列表
1. 创建多维列表
matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]
]
2. 访问元素
matrix[0][1] # → 2(第一行第二列)
3. 修改元素
matrix[2][0] = 77 # 修改第三行第一列为77
六、高级技巧
1. 列表推导式
squares = [x**2 for x in range(10) if x%2 == 0]
# → [0, 4, 16, 36, 64]
2. 浅拷贝 vs 深拷贝
import copyoriginal = [[1,2], [3,4]]
shallow = original.copy() # 浅拷贝(共享子列表)
deep = copy.deepcopy(original) # 深拷贝(完全独立)
3. 列表与生成器
# 列表(直接存储所有元素)
list_data = [x for x in range(1000000)]# 生成器(按需生成,节省内存)
gen_data = (x for x in range(1000000))
七、常见应用场景
-
数据清洗:
raw_data = [" 42 ", "3.14", "NaN", "7"] cleaned = [float(x.strip()) for x in raw_data if x.strip().replace('.','').isdigit()] # → [42.0, 3.14, 7.0]
-
批量处理:
# 批量重命名文件 files = ["a.txt", "b.txt", "c.txt"] new_files = [f"{i}.txt" for i, name in enumerate(files)]
-
算法实现:
# 快速排序 def quicksort(arr):if len(arr) <= 1:return arrpivot = arr[len(arr)//2]return quicksort([x for x in arr if x < pivot]) + \[x for x in arr if x == pivot] + \quicksort([x for x in arr if x > pivot])
八、性能优化
-
尾部操作优先:
append()
/pop()
时间复杂度 O(1)- 头部插入/删除 O(n)(需移动所有元素)
-
避免频繁拼接:
# 低效方式 res = [] for x in big_list:res += [x] # 每次生成新列表# 高效方式 res = [] for x in big_list:res.append(x) # 原地修改
-
预分配空间(大数据量时):
arr = [0] * 1000000 # 预分配百万元素列表
九、常见陷阱
-
可变默认参数:
def bad_append(new_item, my_list=[]): # 危险!默认参数共享my_list.append(new_item)return my_list# 正确做法 def good_append(new_item, my_list=None):if my_list is None:my_list = []my_list.append(new_item)return my_list
-
浅拷贝问题:
a = [[1,2], [3,4]] b = a.copy() # 浅拷贝 b[0][0] = 99 # 修改会影响a
通过掌握这些内容,可以高效处理从简单数据存储到复杂算法实现的各种场景。实际应用中需根据需求选择合适的方法,并注意性能优化和内存管理。