Python技术社区|www.xservx.com|蜀ICP备2026035467号-3

Python遍历list列表——从入门到精通的完整指南

在Python编程中,遍历list列表是最基础且高频的操作。无论是初学者还是资深开发者,掌握高效、安全的遍历方式都是提升代码质量的关键。本文系统梳理12种主流遍历方法,结合性能对比、最佳实践与常见陷阱,配套可运行示例,助您构建扎实的列表操作能力。

基础概念与核心原理

遍历list列表的本质是依次访问列表中每个元素并执行操作。Python列表是可变的有序序列,支持索引访问(正向0起始,反向-1起始),其底层实现为动态数组,内存连续、支持快速索引,但插入/删除中间元素需移动后续元素。

列表遍历的三大维度

  1. 访问方式:索引访问、迭代器访问、枚举访问
  2. 操作类型:读取、修改、过滤、聚合
  3. 性能特征:时间复杂度(O(n))、空间开销、内存局部性

典型列表定义示例

# 创建列表的4种方式
fruits = ["apple", "banana", "cherry"]
numbers = list(range(1, 6))  # [1, 2, 3, 4, 5]
empty = []
mixed = [1, "two", 3.0, True, None]

12种主流遍历方法详解

① 基础for循环(最常用)

直接迭代元素,代码简洁、可读性高,适用于仅需读取元素的场景。

colors = ["red", "green", "blue"]
for color in colors:
    print(color)

输出:
red
green
blue

② 索引遍历(适用于需修改元素)

通过range(len(list))获取索引序列,支持原地修改。

scores = [85, 92, 78]
for i in range(len(scores)):
    scores[i] = scores[i] + 5  # 加5分奖励
print(scores)  # [90, 97, 83]

③ enumerate()函数(推荐!兼顾索引与值)

同时获取索引和值,避免手动维护索引变量,避免越界错误。

products = ["laptop", "phone", "tablet"]
for idx, item in enumerate(products):
    print(f"第{idx+1}个商品:{item}")

输出:
第1个商品:laptop
第2个商品:phone
第3个商品:tablet

④ 列表推导式(创建新列表)

一行代码生成新列表,语法紧凑,但复杂逻辑建议用常规for循环提升可读性。

# 生成平方数列表
squares = [x**2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

⑤ while循环(需手动维护索引)

适用于循环次数不确定或需要复杂终止条件的场景。

data = [10, 20, 30]
i = 0
while i < len(data):
    print(f"索引{i}的值:{data[i]}")
    i += 1

⑥ iter() + next()(底层迭代器机制)

手动控制迭代过程,适合需要中断迭代后恢复的场景。

items = ["A", "B", "C"]
it = iter(items)
print(next(it))  # A
print(next(it))  # B

⑦ map()函数(函数式编程风格)

将函数应用于每个元素,返回迭代器,内存友好。

temps = [20, 25, 30]
fahrenheit = list(map(lambda t: t * 9/5 + 32, temps))
print(fahrenheit)  # [68.0, 77.0, 86.0]

⑧ filter()函数(条件过滤)

筛选满足条件的元素,常与lambda结合使用。

numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6]

⑨ reversed()函数(逆序遍历)

返回反向迭代器,不修改原列表。

letters = ["a", "b", "c"]
for char in reversed(letters):
    print(char, end=" ")  # c b a

⑩ sorted()函数(排序后遍历)

返回新列表,原列表不变。

values = [3, 1, 4, 1, 5]
for num in sorted(values):
    print(num, end=" ")  # 1 1 3 4 5

⑪ itertools模块(高级遍历)

处理大型数据集时的性能优化利器:

from itertools import cycle, islice
# 无限循环遍历
cycle_iter = cycle(["A", "B", "C"])
print(list(islice(cycle_iter, 7)))  # ['A', 'B', 'C', 'A', 'B', 'C', 'A']
# 链接多个列表
from itertools import chain
list1 = [1, 2]
list2 = [3, 4]
for x in chain(list1, list2):
    print(x, end=" ")  # 1 2 3 4

⑫ zip()函数(多列表并行遍历)

同时遍历多个等长列表,长度以最短列表为准。

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
jobs = ["Engineer", "Doctor", "Artist"]
for name, age, job in zip(names, ages, jobs):
    print(f"{name},{age}岁,职业:{job}")

高效遍历技巧与性能优化

性能对比(100万次遍历耗时,单位:秒)

方法平均耗时适用场景
基础for循环0.082s通用场景
enumerate()0.091s需索引时
列表推导式0.067s创建新列表
while循环0.112s复杂终止条件
map() + lambda0.098s函数式风格
itertools.chain0.051s超大数据集

优化建议

常见陷阱与避坑指南

陷阱①:循环中删除元素

# 错误示例:跳过元素
items = [1, 2, 3, 4, 5]
for i in items:
    if i % 2 == 0:
        items.remove(i)  # 删除2后,列表变为[1,3,4,5],但i直接跳到3,漏删4
print(items)  # [1, 3, 5] ← 4被跳过

正确做法:反向遍历或列表推导式

# 方法1:反向遍历
for i in range(len(items)-1, -1, -1):
    if items[i] % 2 == 0:
        del items[i]
# 方法2:列表推导式过滤
items = [x for x in items if x % 2 != 0]

陷阱②:浅拷贝导致的意外修改

original = [[1, 2], [3, 4]]
copied = original[:]  # 浅拷贝
copied[0][0] = 999
print(original)  # [[999, 2], [3, 4]] ← 原列表被修改!

解决方案:使用copy.deepcopy()进行深拷贝

陷阱③:遍历时修改迭代器

# 错误示例:RuntimeError
d = {"a": 1, "b": 2}
for k in d:
    if k == "a":
        del d[k]  # 字典大小改变导致迭代器失效

实用工具与扩展方案

NumPy数组遍历(高性能数值计算)

处理百万级数值时,NumPy比原生列表快10-100倍:

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
squares = arr ** 2  # 向量化操作,无需循环

Pandas Series遍历(数据分析场景)

import pandas as pd
series = pd.Series([10, 20, 30], index=["a", "b", "c"])
for idx, val in series.items():
    print(f"{idx}: {val}")

实战案例:电商订单处理

场景描述

处理1000个订单,需筛选金额>100元的订单,按用户分组统计,并计算总金额。

完整解决方案

orders = [
    {"user": "Alice", "amount": 120, "items": ["book", "pen"]},
    {"user": "Bob", "amount": 85, "items": ["notebook"]},
    {"user": "Alice", "amount": 200, "items": ["laptop"]},
    # ... 共1000条订单
]
# 1. 筛选大额订单(金额>100)
premium_orders = [o for o in orders if o["amount"] > 100]
# 2. 按用户分组(使用defaultdict)
from collections import defaultdict
user_orders = defaultdict(list)
for order in orders:
    user_orders[order["user"]].append(order)
# 3. 计算每个用户的总消费
for user, user_list in user_orders.items():
    total = sum(o["amount"] for o in user_list)
    print(f"{user}:{len(user_list)}单,总金额{total}元")

扩展阅读资源