Python 列表操作
列表简介
列表是Python中最常用的数据结构之一,它是一个可变的有序集合,可以存储不同类型的数据项。在Python中,列表用方括号[]
表示,各元素之间用逗号,
分隔。
列表的特点:
- 有序:元素按特定顺序排列
- 可变:可以修改、添加、删除元素
- 异构:可以存储不同类型的数据
- 索引访问:使用索引可以访问特定位置的元素
创建列表
基本创建方法
python
# 空列表
empty_list = []
# 包含整数的列表
numbers = [1, 2, 3, 4, 5]
# 混合类型列表
mixed = [1, "Hello", 3.14, True]
# 嵌套列表
nested = [1, [2, 3], [4, 5, 6]]
使用列表推导式
列表推导式是一种创建列表的简洁方法:
python
# 生成1到10的平方列表
squares = [x**2 for x in range(1, 11)]
print(squares) # 输出: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 带条件的列表推导式
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares) # 输出: [4, 16, 36, 64, 100]
使用list()
函数
python
# 从字符串创建列表
list_from_string = list("Python")
print(list_from_string) # 输出: ['P', 'y', 't', 'h', 'o', 'n']
# 从range创建列表
list_from_range = list(range(5))
print(list_from_range) # 输出: [0, 1, 2, 3, 4]
访问列表元素
索引访问
Python列表的索引从0开始。可以使用正索引从前向后访问,也可以使用负索引从后向前访问。
python
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
# 正索引访问
print(fruits[0]) # 输出: apple
print(fruits[2]) # 输出: cherry
# 负索引访问
print(fruits[-1]) # 输出: elderberry (最后一个元素)
print(fruits[-3]) # 输出: cherry (倒数第三个元素)
切片操作
切片语法为[start:end:step]
,其中start
是起始索引(包含),end
是结束索引(不包含),step
是步长。
python
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 基本切片
print(numbers[2:5]) # 输出: [2, 3, 4]
# 省略起始索引,从头开始
print(numbers[:5]) # 输出: [0, 1, 2, 3, 4]
# 省略结束索引,到尾结束
print(numbers[5:]) # 输出: [5, 6, 7, 8, 9]
# 带步长的切片
print(numbers[1:8:2]) # 输出: [1, 3, 5, 7]
# 负步长,反向切片
print(numbers[::-1]) # 输出: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
修改列表
更改单个元素
python
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits) # 输出: ['apple', 'blueberry', 'cherry']
通过切片更改多个元素
python
numbers = [0, 1, 2, 3, 4]
numbers[1:4] = [10, 20, 30]
print(numbers) # 输出: [0, 10, 20, 30, 4]
# 可以插入不同数量的元素
numbers[1:2] = [5, 6, 7]
print(numbers) # 输出: [0, 5, 6, 7, 20, 30, 4]
列表操作方法
添加元素
python
fruits = ["apple", "banana"]
# append() - 在列表末尾添加一个元素
fruits.append("cherry")
print(fruits) # 输出: ['apple', 'banana', 'cherry']
# insert() - 在指定位置插入元素
fruits.insert(1, "orange")
print(fruits) # 输出: ['apple', 'orange', 'banana', 'cherry']
# extend() - 将另一个列表的元素添加到列表末尾
more_fruits = ["grape", "kiwi"]
fruits.extend(more_fruits)
print(fruits) # 输出: ['apple', 'orange', 'banana', 'cherry', 'grape', 'kiwi']
删除元素
python
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
# remove() - 删除指定值的第一个匹配项
fruits.remove("banana")
print(fruits) # 输出: ['apple', 'cherry', 'date', 'elderberry']
# pop() - 删除并返回指定位置的元素(默认为最后一个)
removed = fruits.pop()
print(removed) # 输出: elderberry
print(fruits) # 输出: ['apple', 'cherry', 'date']
removed = fruits.pop(1)
print(removed) # 输出: cherry
print(fruits) # 输出: ['apple', 'date']
# del语句 - 删除指定的元素或切片
del fruits[0]
print(fruits) # 输出: ['date']
numbers = [0, 1, 2, 3, 4, 5]
del numbers[1:4]
print(numbers) # 输出: [0, 4, 5]
# clear() - 删除所有元素
fruits.clear()
print(fruits) # 输出: []
查找元素
python
fruits = ["apple", "banana", "cherry", "banana", "date"]
# in 运算符 - 检查元素是否存在
print("banana" in fruits) # 输出: True
print("kiwi" in fruits) # 输出: False
# index() - 返回第一个匹配项的索引
print(fruits.index("banana")) # 输出: 1
# 指定开始和结束范围
print(fruits.index("banana", 2)) # 输出: 3 (从索引2开始查找)
# count() - 计算元素出现的次数
print(fruits.count("banana")) # 输出: 2
print(fruits.count("kiwi")) # 输出: 0
排序和反转
python
numbers = [3, 1, 4, 1, 5, 9, 2]
# sort() - 原地排序
numbers.sort()
print(numbers) # 输出: [1, 1, 2, 3, 4, 5, 9]
# 降序排序
numbers.sort(reverse=True)
print(numbers) # 输出: [9, 5, 4, 3, 2, 1, 1]
# 使用自定义函数排序
fruits = ["apple", "banana", "Cherry", "Date"]
fruits.sort(key=str.lower) # 忽略大小写排序
print(fruits) # 输出: ['apple', 'banana', 'Cherry', 'Date']
# reverse() - 反转列表
fruits.reverse()
print(fruits) # 输出: ['Date', 'Cherry', 'banana', 'apple']
# sorted() - 返回排序后的新列表,不改变原列表
original = [3, 1, 4, 1, 5]
sorted_list = sorted(original)
print(original) # 输出: [3, 1, 4, 1, 5]
print(sorted_list) # 输出: [1, 1, 3, 4, 5]
列表的其他操作
列表复制
python
# 浅拷贝的几种方式
original = [1, 2, 3]
# 使用切片
copy1 = original[:]
# 使用list()函数
copy2 = list(original)
# 使用copy()方法
copy3 = original.copy()
# 示例
original.append(4)
print(original) # 输出: [1, 2, 3, 4]
print(copy3) # 输出: [1, 2, 3]
# 深拷贝
import copy
nested = [1, [2, 3]]
deep_copy = copy.deepcopy(nested)
nested[1].append(4)
print(nested) # 输出: [1, [2, 3, 4]]
print(deep_copy) # 输出: [1, [2, 3]]
列表推导式进阶
python
# 嵌套循环的列表推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [x for row in matrix for x in row]
print(flattened) # 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 条件筛选和转换
words = ["apple", "banana", "kiwi", "cherry", "date"]
long_fruits = [word.upper() for word in words if len(word) > 5]
print(long_fruits) # 输出: ['BANANA', 'CHERRY']
列表性能考量
提示
对于需要频繁在开头插入或删除元素的场景,考虑使用collections.deque
替代列表,它在这些操作上性能更好。
python
from collections import deque
queue = deque(["apple", "banana", "cherry"])
queue.appendleft("orange")
print(queue) # 输出: deque(['orange', 'apple', 'banana', 'cherry'])
实际应用案例
案例1:待办事项管理器
python
# 简单的待办事项管理器
todo_list = []
def add_task(task):
todo_list.append({"task": task, "completed": False})
print(f"任务 '{task}' 已添加。")
def complete_task(index):
if 0 <= index < len(todo_list):
todo_list[index]["completed"] = True
print(f"任务 '{todo_list[index]['task']}' 标记为已完成。")
else:
print("无效的任务索引。")
def remove_task(index):
if 0 <= index < len(todo_list):
task = todo_list.pop(index)
print(f"任务 '{task['task']}' 已删除。")
else:
print("无效的任务索引。")
def show_tasks():
if not todo_list:
print("待办事项列表为空。")
return
print("\n待办事项列表:")
for i, item in enumerate(todo_list):
status = "✓" if item["completed"] else "✗"
print(f"{i}. [{status}] {item['task']}")
print()
# 使用示例
add_task("学习Python列表")
add_task("完成作业")
add_task("购物")
show_tasks()
complete_task(0)
show_tasks()
remove_task(2)
show_tasks()
输出结果:
任务 '学习Python列表' 已添加。
任务 '完成作业' 已添加。
任务 '购物' 已添加。
待办事项列表:
0. [✗] 学习Python列表
1. [✗] 完成作业
2. [✗] 购物
任务 '学习Python列表' 标记为已完成。
待办事项列表:
0. [✓] 学习Python列表
1. [✗] 完成作业
2. [✗] 购物
任务 '购物' 已删除。
待办事项列表:
0. [✓] 学习Python列表
1. [✗] 完成作业
案例2:数据分析
python
# 简单的销售数据分析
sales_data = [
{"product": "笔记本电脑", "price": 5999, "units": 10},
{"product": "手机", "price": 3999, "units": 25},
{"product": "耳机", "price": 999, "units": 50},
{"product": "平板电脑", "price": 2999, "units": 15},
{"product": "键盘", "price": 599, "units": 30}
]
# 计算每种产品的总销售额
total_sales = [item["price"] * item["units"] for item in sales_data]
print("各产品销售额:", total_sales)
# 计算总销售额
total_revenue = sum(total_sales)
print(f"总销售额: {total_revenue}")
# 找出销售额最高的产品
max_sales_index = total_sales.index(max(total_sales))
best_selling = sales_data[max_sales_index]["product"]
print(f"销售额最高的产品: {best_selling},销售额: {max(total_sales)}")
# 按销售额排序产品
sorted_products = [x for _, x in sorted(zip(total_sales, [item["product"] for item in sales_data]), reverse=True)]
print("按销售额排序的产品:", sorted_products)
输出结果:
各产品销售额: [59990, 99975, 49950, 44985, 17970]
总销售额: 272870
销售额最高的产品: 手机,销售额: 99975
按销售额排序的产品: ['手机', '笔记本电脑', '耳机', '平板电脑', '键盘']
列表进阶技巧
使用zip()
合并列表
python
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["New York", "London", "Paris"]
# 合并三个列表
combined = list(zip(names, ages, cities))
print(combined)
# 输出: [('Alice', 25, 'New York'), ('Bob', 30, 'London'), ('Charlie', 35, 'Paris')]
# 解压缩
n, a, c = zip(*combined)
print(n) # 输出: ('Alice', 'Bob', 'Charlie')
print(a) # 输出: (25, 30, 35)
print(c) # 输出: ('New York', 'London', 'Paris')
列表的过滤与映射
除了列表推导式,我们还可以使用内置函数filter()
和map()
:
python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 使用filter获取偶数
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # 输出: [2, 4, 6, 8, 10]
# 使用map对每个元素求平方
squares = list(map(lambda x: x**2, numbers))
print(squares) # 输出: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
总结
Python列表是一种极其灵活和强大的数据结构,适用于各种编程场景。在本文中,我们学习了:
- 创建列表的多种方式
- 访问和修改列表元素
- 列表的常用操作(添加、删除、查找、排序等)
- 列表复制、推导式和性能考量
- 实际应用案例
- 进阶技巧
通过掌握这些操作,你将能够在Python编程中高效地管理和操作数据集合。
练习题
- 编写一个函数,接受一个列表作为参数,返回列表中的最大值和最小值(不使用内置函数
max()
和min()
)。 - 将两个有序列表合并成一个新的有序列表。
- 编写一个函数,找出列表中的所有重复元素。
- 实现一个简单的购物车程序,可以添加商品、删除商品、查看购物车和计算总价。
- 编写一个函数,将一个嵌套列表(列表的列表)转置。例如,将
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
转换为[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
。
学习建议
掌握列表操作需要大量的练习和实践。尝试在实际项目中运用这些知识,并尝试解决更多与列表相关的编程问题。