Python列表创建操作与遍历指南
Python 列表全方位解析:创建、操作、删除与遍历的全面指南
列表(List)是 Python 中最灵活且常用的数据结构之一,支持动态增删元素、混合数据类型存储以及高效的遍历操作。以下从 创建、操作、删除、遍历 四个核心维度详细解析列表的使用方法,并附上代码示例。
一、创建列表
列表用方括号 [] 定义,元素间用逗号分隔,支持任意数据类型。
- 基础创建
python
# 空列表
empty_list = []
# 包含元素的列表
numbers = [1, 2, 3, 4]
mixed = [10, "hello", 3.14, True]
# 使用 list() 构造函数
from_string = list("Python") # 输出: ['P', 'y', 't', 'h', 'o', 'n']
- 生成式创建
python
# 生成 0-9 的平方列表
squares = [x**2 for x in range(10)]
# 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件的生成式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# 输出: [0, 4, 16, 36, 64]
二、操作列表
- 访问元素
O 索引从 0 开始,支持负数索引(从末尾反向计数)。
O 切片操作 list[start:end:step]。
python
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[1]) # 输出: banana
print(fruits[-1]) # 输出: date
print(fruits[1:3]) # 输出: ['banana', 'cherry']
print(fruits[::-1]) # 输出: ['date', 'cherry', 'banana', 'apple'](反转列表)
- 修改元素
python
# 直接通过索引修改
fruits[0] = "avocado" # 列表变为 ["avocado", "banana", "cherry", "date"]
# 通过切片替换多个元素
fruits[1:3] = ["blueberry", "coconut"] # 替换索引1和2的元素
- 添加元素
O append():在末尾添加单个元素。
O extend():添加多个元素(合并另一个列表)。
O insert():在指定位置插入元素。
python
numbers = [1, 2, 3]
numbers.append(4) # [1, 2, 3, 4]
numbers.extend([5, 6]) # [1, 2, 3, 4, 5, 6]
numbers.insert(0, 0) # 在索引0插入0 → [0, 1, 2, 3, 4, 5, 6]
- 合并列表
python
list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2 # [1, 2, 3, 4]
list1 *= 2 # list1变为 [1, 2, 1, 2]
三、删除元素
- 按值删除
python
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana") # 删除第一个匹配的元素 → ["apple", "cherry"]
- 按索引删除
python
# pop() 删除并返回元素(默认删除最后一个)
last_fruit = fruits.pop() # 返回 "cherry",列表变为 ["apple"]
# del 语句删除元素或切片
del fruits[0] # 列表变为空列表 []
del fruits[1:3] # 删除切片范围内的元素
- 清空列表
python
numbers = [1, 2, 3]
numbers.clear() # 清空列表 → []
四、遍历列表
- 基本遍历
python
colors = ["red", "green", "blue"]
for color in colors:
print(color)
- 带索引遍历
python
for index, color in enumerate(colors):
print(f"索引 {index}: {color}")
- 列表生成式遍历
python
uppercase_colors = [color.upper() for color in colors] # 转换为大写列表
- 结合 zip 遍历多个列表
python
names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
五、高级技巧
- 深拷贝与浅拷贝
python
import copy
original = [[1, 2], [3, 4]]
shallow_copy = original.copy() # 浅拷贝:嵌套列表仍共享引用
deep_copy = copy.deepcopy(original) # 深拷贝:完全独立副本
- 列表作为函数参数
python
def modify_list(lst):
lst.append(100) # 会修改原列表(列表是可变对象)
my_list = [1, 2, 3]
modify_list(my_list) # my_list变为 [1, 2, 3, 100]
- 性能注意点
- append() 和 pop() 的时间复杂度为 O(1)。
- insert(0, x) 和 pop(0) 的时间复杂度为 O(n)(避免频繁使用)。
- 排序与反转
python
numbers = [3, 1, 4, 1, 5]
numbers.sort() # 原地排序 → [1, 1, 3, 4, 5]
reversed_numbers = sorted(numbers, reverse=True) # 生成新列表 → [5, 4, 3, 1, 1]
numbers.reverse() # 原地反转 → [5, 4, 3, 1, 1]
六、常见使用场景
- 数据收集与处理
python
# 过滤偶数
numbers = [x for x in range(10) if x % 2 == 0]
- 临时存储结构
python
# 实现栈(后进先出)
stack = []
stack.append(1) # 入栈
stack.pop() # 出栈 → 1
# 实现队列(先进先出,建议用 collections.deque)
queue = []
queue.append(1) # 入队
queue.pop(0) # 出队 → 1(效率较低)
通过掌握上述方法,您将能高效利用 Python 列表解决各类数据处理问题。列表的灵活性和易用性使其成为日常编程中的核心工具。