Python列表操作详解
一、列表基础回顾
列表(List)是Python中最常用的数据结构之一,具有以下特点:
- 有序的:元素按插入顺序存储
- 可变的:可以修改、添加或删除元素
- 异构的:可以包含不同类型的元素
- 可重复的:允许包含重复的元素
# 列表定义示例
my_list = [1, "hello", 3.14, True] # 包含不同类型元素
numbers = [10, 20, 30, 40, 50] # 同类型元素
empty_list = [] # 空列表
二、获取列表元素个数
使用len()
函数获取列表长度(元素个数):
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # 输出: 3
注意:len()
是Python内置函数,适用于多种数据类型(字符串、元组、列表等)
三、查找和统计元素
1. count()方法 - 统计元素出现次数
numbers = [1, 2, 3, 2, 4, 2, 5]
print(numbers.count(2)) # 输出: 3
print(numbers.count(7)) # 输出: 0 (元素不存在)
2. index()方法 - 查找元素位置
fruits = ["apple", "banana", "cherry", "banana"]
# 基本用法
print(fruits.index("banana")) # 输出: 1
# 指定查找范围
print(fruits.index("banana", 2)) # 输出: 3 (从索引2开始查找)
# 处理元素不存在的情况
try:
print(fruits.index("orange"))
except ValueError as e:
print(f"错误: {e}") # 输出: 'orange' is not in list
四、增加元素
1. append() - 在末尾添加单个元素
colors = ["red", "green"]
colors.append("blue")
print(colors) # 输出: ['red', 'green', 'blue']
# 添加列表作为单个元素
colors.append(["yellow", "purple"])
print(colors) # 输出: ['red', 'green', 'blue', ['yellow', 'purple']]
2. extend() - 扩展列表(添加多个元素)
numbers = [1, 2, 3]
numbers.extend([4, 5, 6])
print(numbers) # 输出: [1, 2, 3, 4, 5, 6]
# 与append的区别
letters = ['a', 'b']
letters.append(['c', 'd']) # 添加整个列表作为单个元素
print(letters) # 输出: ['a', 'b', ['c', 'd']]
letters = ['a', 'b']
letters.extend(['c', 'd']) # 添加列表中的每个元素
print(letters) # 输出: ['a', 'b', 'c', 'd']
3. insert() - 在指定位置插入元素
fruits = ["apple", "banana", "cherry"]
# 在索引1处插入"orange"
fruits.insert(1, "orange")
print(fruits) # 输出: ['apple', 'orange', 'banana', 'cherry']
# 索引超出范围时
fruits.insert(10, "pear") # 相当于append
print(fruits) # 输出: ['apple', 'orange', 'banana', 'cherry', 'pear']
fruits.insert(-1, "grape") # 负数索引
print(fruits) # 输出: ['apple', 'orange', 'banana', 'cherry', 'grape', 'pear']
五、删除元素
1. del语句 - 删除指定索引的元素
numbers = [10, 20, 30, 40, 50]
del numbers[1] # 删除索引1的元素
print(numbers) # 输出: [10, 30, 40, 50]
# 删除整个列表
del numbers
# print(numbers) # 会报错: NameError: name 'numbers' is not defined
2. remove() - 删除第一个匹配的元素
fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana")
print(fruits) # 输出: ['apple', 'cherry', 'banana']
# 处理元素不存在的情况
try:
fruits.remove("orange")
except ValueError as e:
print(f"错误: {e}") # 输出: list.remove(x): x not in list
3. pop() - 删除并返回指定索引的元素
numbers = [10, 20, 30, 40]
# 不指定索引,删除最后一个元素
last_num = numbers.pop()
print(last_num) # 输出: 40
print(numbers) # 输出: [10, 20, 30]
# 指定索引
second_num = numbers.pop(1)
print(second_num) # 输出: 20
print(numbers) # 输出: [10, 30]
# 索引超出范围
try:
numbers.pop(5)
except IndexError as e:
print(f"错误: {e}") # 输出: pop index out of range
4. clear() - 清空列表
items = ["book", "pen", "laptop"]
items.clear()
print(items) # 输出: []
# 与del的区别
items = ["book", "pen", "laptop"]
del items
# print(items) # 会报错: NameError
六、列表排序
1. sort() - 原地排序
numbers = [5, 2, 8, 1, 3]
# 默认升序排序
numbers.sort()
print(numbers) # 输出: [1, 2, 3, 5, 8]
# 降序排序
numbers.sort(reverse=True)
print(numbers) # 输出: [8, 5, 3, 2, 1]
# 字符串排序
words = ["banana", "apple", "cherry", "date"]
words.sort()
print(words) # 输出: ['apple', 'banana', 'cherry', 'date']
2. 使用key参数自定义排序
# 按字符串长度排序
words = ["apple", "banana", "cherry", "date"]
words.sort(key=len)
print(words) # 输出: ['date', 'apple', 'banana', 'cherry']
# 复杂数据结构排序
students = [
{"name": "Tom", "age": 22},
{"name": "Jack", "age": 18},
{"name": "Rose", "age": 25}
]
# 按年龄排序
students.sort(key=lambda x: x["age"])
print(students)
# 输出: [{'name': 'Jack', 'age': 18}, {'name': 'Tom', 'age': 22}, {'name': 'Rose', 'age': 25}]
# 按姓名排序
students.sort(key=lambda x: x["name"])
print(students)
# 输出: [{'name': 'Jack', 'age': 18}, {'name': 'Rose', 'age': 25}, {'name': 'Tom', 'age': 22}]
3. sorted() - 返回新排序列表(不修改原列表)
numbers = [5, 2, 8, 1, 3]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # 输出: [1, 2, 3, 5, 8]
print(numbers) # 输出: [5, 2, 8, 1, 3] (原列表未改变)
七、其他常用操作
1. 列表切片
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[::2]) # 输出: [0, 2, 4, 6, 8]
print(numbers[1::2]) # 输出: [1, 3, 5, 7, 9]
# 反转列表
print(numbers[::-1]) # 输出: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
2. 列表复制
original = [1, 2, 3]
# 浅拷贝
copy1 = original.copy()
copy2 = list(original)
copy3 = original[:]
# 修改拷贝不会影响原列表
copy1.append(4)
print(original) # 输出: [1, 2, 3]
print(copy1) # 输出: [1, 2, 3, 4]
# 注意嵌套列表的情况
nested = [[1, 2], [3, 4]]
shallow_copy = nested.copy()
shallow_copy[0].append(5)
print(nested) # 输出: [[1, 2, 5], [3, 4]] (原列表被修改)
3. 列表拼接
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# 使用+运算符
combined = list1 + list2
print(combined) # 输出: [1, 2, 3, 4, 5, 6]
# 使用*运算符重复
repeated = list1 * 3
print(repeated) # 输出: [1, 2, 3, 1, 2, 3, 1, 2, 3]
八、总结
列表操作方法速查表
操作类型 | 方法/函数 | 描述 |
---|---|---|
获取长度 | len(list) | 返回列表元素个数 |
统计 | list.count(x) | 返回x在列表中出现的次数 |
查找 | list.index(x) | 返回x第一次出现的索引 |
添加 | list.append(x) | 在末尾添加单个元素 |
扩展 | list.extend(iterable) | 在末尾添加多个元素 |
插入 | list.insert(i, x) | 在指定位置插入元素 |
删除 | del list[i] | 删除指定索引的元素 |
删除 | list.remove(x) | 删除第一个匹配的元素 |
删除 | list.pop([i]) | 删除并返回指定索引的元素 |
清空 | list.clear() | 移除所有元素 |
排序 | list.sort() | 对列表进行原地排序 |
排序 | sorted(list) | 返回新排序列表 |
最佳实践建议
- 当需要频繁在序列中间插入/删除元素时,考虑使用
collections.deque
- 对大型列表排序时,
sorted()
比.sort()
更安全(不修改原列表) - 使用列表推导式可以更简洁地创建和转换列表
- 当需要确保元素唯一性时,考虑使用集合(set)
- 对于只读操作,元组(tuple)比列表更高效
通过掌握这些列表操作方法,你将能够高效地处理Python中的序列数据。列表是Python编程中最基础也最重要的数据结构之一,建议多加练习以熟练掌握。