列表(List)是 Python 中最常用、最灵活的数据结构之一,它可以存储任意类型的元素,并且支持动态修改。本文将全面介绍 Python 列表的创建、操作、方法和高级用法,配有丰富的代码示例。
一、列表基础
1. 创建列表
python# 空列表empty_list = []empty_list2 = list()# 包含元素的列表numbers = [1, 2, 3, 4, 5]fruits = ['apple', 'banana', 'orange']mixed = [1, 'hello', 3.14, True]# 多维列表(列表的列表)matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2. 访问列表元素
pythonfruits = ['apple', 'banana', 'orange', 'grape']# 通过索引访问(从0开始)print(fruits[0]) # 输出: appleprint(fruits[2]) # 输出: orange# 负索引表示从末尾开始print(fruits[-1]) # 输出: grapeprint(fruits[-2]) # 输出: orange# 切片操作 [start:end:step]print(fruits[1:3]) # 输出: ['banana', 'orange']print(fruits[:2]) # 输出: ['apple', 'banana']print(fruits[2:]) # 输出: ['orange', 'grape']print(fruits[::2]) # 输出: ['apple', 'orange']print(fruits[::-1]) # 输出: ['grape', 'orange', 'banana', 'apple'] (反转列表)
二、列表操作
1. 修改列表
pythonnumbers = [1, 2, 3, 4, 5]# 修改单个元素numbers[1] = 20print(numbers) # [1, 20, 3, 4, 5]# 修改多个元素(切片赋值)numbers[1:4] = [22, 33, 44]print(numbers) # [1, 22, 33, 44, 5]# 替换的元素数量可以不同numbers[1:4] = [99, 88]print(numbers) # [1, 99, 88, 5]
2. 添加元素
pythonfruits = ['apple', 'banana']# append() - 在末尾添加单个元素fruits.append('orange')print(fruits) # ['apple', 'banana', 'orange']# insert() - 在指定位置插入元素fruits.insert(1, 'grape')print(fruits) # ['apple', 'grape', 'banana', 'orange']# extend() - 合并列表(相当于 +=)more_fruits = ['pear', 'peach']fruits.extend(more_fruits)print(fruits) # ['apple', 'grape', 'banana', 'orange', 'pear', 'peach']# + 运算符也可以合并列表new_fruits = fruits + ['melon', 'kiwi']print(new_fruits)
3. 删除元素
pythonnumbers = [1, 2, 3, 4, 5]# del 语句 - 按索引删除del numbers[1]print(numbers) # [1, 3, 4, 5]# pop() - 删除并返回指定位置的元素(默认最后一个)removed = numbers.pop()print(removed) # 5print(numbers) # [1, 3, 4]removed = numbers.pop(0)print(removed) # 1print(numbers) # [3, 4]# remove() - 按值删除(删除第一个匹配项)letters = ['a', 'b', 'c', 'a']letters.remove('a')print(letters) # ['b', 'c', 'a']# clear() - 清空列表letters.clear()print(letters) # []
三、列表方法
1. 常用方法
pythonnums = [3, 1, 4, 1, 5, 9, 2]# count() - 统计元素出现次数print(nums.count(1)) # 2# index() - 返回元素第一次出现的索引print(nums.index(5)) # 4# reverse() - 反转列表(原地修改)nums.reverse()print(nums) # [2, 9, 5, 1, 4, 1, 3]# sort() - 排序(原地修改)nums.sort()print(nums) # [1, 1, 2, 3, 4, 5, 9]# sorted() - 返回排序后的新列表(不修改原列表)nums = [3, 1, 4, 1, 5, 9, 2]sorted_nums = sorted(nums)print(nums) # [3, 1, 4, 1, 5, 9, 2] (未修改)print(sorted_nums) # [1, 1, 2, 3, 4, 5, 9]
2. 排序进阶
python# 自定义排序students = [{'name': 'Alice', 'score': 85},{'name': 'Bob', 'score': 92},{'name': 'Charlie', 'score': 78}]# 按分数升序排序students.sort(key=lambda x: x['score'])print(students)# 按分数降序排序students.sort(key=lambda x: x['score'], reverse=True)print(students)# 使用 cmp 参数(Python3 中需要 functools.cmp_to_key)from functools import cmp_to_keydef compare(a, b):if a['score'] < b['score']:return -1elif a['score'] > b['score']:return 1else:return 0students.sort(key=cmp_to_key(compare))print(students)
四、列表推导式
列表推导式是 Python 中创建列表的简洁方式。
1. 基本列表推导式
python# 创建0-9的平方列表squares = [x**2 for x in range(10)]print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]# 带条件的列表推导式even_squares = [x**2 for x in range(10) if x % 2 == 0]print(even_squares) # [0, 4, 16, 36, 64]
2. 嵌套列表推导式
python# 创建乘法表matrix = [[i*j for j in range(1, 6)] for i in range(1, 6)]for row in matrix:print(row)# 输出:# [1, 2, 3, 4, 5]# [2, 4, 6, 8, 10]# [3, 6, 9, 12, 15]# [4, 8, 12, 16, 20]# [5, 10, 15, 20, 25]# 展平二维列表flat = [num for row in matrix for num in row]print(flat) # [1, 2, 3, 4, 5, 2, 4, 6, 8, 10, ...]
五、列表高级操作
1. 列表复制
pythonoriginal = [1, 2, [3, 4]]# 浅拷贝(shallow copy)shallow_copy = original.copy() # 或 original[:] 或 list(original)shallow_copy[0] = 10shallow_copy[2][0] = 30print(original) # [1, 2, [30, 4]] (嵌套列表被修改)# 深拷贝(deep copy)import copydeep_copy = copy.deepcopy(original)deep_copy[2][0] = 300print(original) # [1, 2, [30, 4]] (不受影响)
2. 列表与迭代
python# enumerate() - 获取索引和值fruits = ['apple', 'banana', 'orange']for index, fruit in enumerate(fruits):print(f"{index}: {fruit}")# zip() - 合并多个列表names = ['Alice', 'Bob', 'Charlie']ages = [25, 30, 35]for name, age in zip(names, ages):print(f"{name} is {age} years old")# filter() - 过滤列表numbers = [1, 2, 3, 4, 5, 6]even_numbers = list(filter(lambda x: x % 2 == 0, numbers))print(even_numbers) # [2, 4, 6]# map() - 应用函数到每个元素squared = list(map(lambda x: x**2, numbers))print(squared) # [1, 4, 9, 16, 25, 36]
3. 列表与解包
python# 解包列表first, *middle, last = [1, 2, 3, 4, 5]print(first) # 1print(middle) # [2, 3, 4]print(last) # 5# 交换变量a, b = 1, 2a, b = b, aprint(a, b) # 2 1# 合并列表list1 = [1, 2, 3]list2 = ['a', 'b', 'c']combined = [*list1, *list2]print(combined) # [1, 2, 3, 'a', 'b', 'c']
六、实际应用示例
1. 数据处理示例
python# 计算学生平均分students = [{'name': 'Alice', 'scores': [85, 90, 78]},{'name': 'Bob', 'scores': [92, 88, 91]},{'name': 'Charlie', 'scores': [78, 82, 85]}]# 计算每个学生的平均分for student in students:avg = sum(student['scores']) / len(student['scores'])student['average'] = avgprint(students)# 输出:# [# {'name': 'Alice', 'scores': [85, 90, 78], 'average': 84.333...},# {'name': 'Bob', 'scores': [92, 88, 91], 'average': 90.333...},# {'name': 'Charlie', 'scores': [78, 82, 85], 'average': 81.666...}# ]
2. 矩阵操作示例
python# 矩阵转置matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]transposed = [[row[i] for row in matrix] for i in range(3)]print(transposed)# 输出:# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]# 或者使用 zip()transposed_zip = list(zip(*matrix))print(transposed_zip) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)] (元组形式)
3. 扁平化嵌套列表
pythondef flatten(nested_list):flat_list = []for item in nested_list:if isinstance(item, list):flat_list.extend(flatten(item))else:flat_list.append(item)return flat_listnested = [1, [2, [3, 4], 5], 6]print(flatten(nested)) # [1, 2, 3, 4, 5, 6]
七、性能考虑
1. 列表操作的时间复杂度
- 访问元素:O(1)
- 修改元素:O(1)
- 尾部添加:O(1)(平均)
- 头部添加/删除:O(n)
- 切片操作:O(k)(k是切片长度)
- 排序:O(n log n)
- 包含检查:O(n)
2. 何时使用列表
- 需要有序集合
- 需要频繁访问或修改元素
- 需要动态调整大小
- 不需要频繁的包含检查(如果需要快速查找,考虑使用集合或字典)
八、总结
列表是 Python 中最强大和常用的数据结构之一,掌握它的各种操作和技巧可以大大提高你的编程效率。本文涵盖了:
- 列表的创建和基本访问
- 添加、修改和删除元素的方法
- 常用的列表方法(sort, reverse, count等)
- 列表推导式的高级用法
- 列表的复制、解包和迭代
- 实际应用中的数据处理示例
- 性能考虑和最佳实践
通过不断练习这些概念,你将能够更高效地使用列表来解决各种编程问题。记住,列表是可变的,这意味着对列表的修改会影响所有引用该列表的变量,这在需要独立副本时需要注意使用深拷贝或浅拷贝。