一文掌握如何在 Python 中遍历列表
列表在 Python 编程中无处不在 — 从存储用户数据到管理应用程序状态。让我们探索遍历列表的所有实用方法,并提供清晰的示例和使用每种方法的真实情况。
经典的 For 循环
遍历列表最直接的方法是使用 'for' 循环:
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# orange
当您需要时,此方法是完美的:
- 按顺序阅读每个项目
- 不需要索引
- 需要干净、可读的代码
当你需要索引时:enumerate()
有时,您需要该项目及其在列表中的位置:
tasks = ['Write email', 'Call client', 'Update report']
for index, task in enumerate(tasks):
print(f"Task {index + 1}: {task}")
# Output:
# Task 1: Write email
# Task 2: Call client
# Task 3: Update report
# Start counting from a different number
for index, task in enumerate(tasks, start=1):
print(f"Task {index}: {task}")
# Output:
# Task 1: Write email
# Task 2: Call client
# Task 3: Update report
'enumerate()' 在以下情况下特别有用:
- 创建编号列表
- 跟踪项目位置
- 按索引查找特定项目
遍历多个列表:zip()
需要一次处理多个列表?'zip()' 是你的朋友:
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
subjects = ['Math', 'Science', 'History']
for name, score, subject in zip(names, scores, subjects):
print(f"{name} got {score} in {subject}")
# Output:
# Alice got 85 in Math
# Bob got 92 in Science
# Charlie got 78 in History
# Handle lists of different lengths with zip_longest
from itertools import zip_longest
extra_names = ['Alice', 'Bob', 'Charlie', 'David']
scores = [85, 92, 78]
for name, score in zip_longest(extra_names, scores, fillvalue='No score'):
print(f"{name}: {score}")
# Output:
# Alice: 85
# Bob: 92
# Charlie: 78
# David: No score
此方法适用于:
- 跨列表比较项目
- 一起处理相关数据
- 从并行列表创建词典
列表推导式:当你需要一个新列表时
当您想根据现有数据创建新列表时:
# Convert temperatures from Celsius to Fahrenheit
celsius = [0, 10, 20, 30, 40]
fahrenheit = [c * 9/5 + 32 for c in celsius]
print(fahrenheit)
# Output: [32.0, 50.0, 68.0, 86.0, 104.0]
# Filter even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [n for n in numbers if n % 2 == 0]
print(evens)
# Output: [2, 4, 6, 8, 10]
# Create a list of tuples
points = [(x, y) for x in range(3) for y in range(2)]
print(points)
# Output: [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
列表推导式非常适合:
- 数据转换
- 筛选列表
- 创建新的数据结构
使用步骤循环:切片表示法
需要跳过项目或倒退?使用切片表示法:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Every second number
for num in numbers[::2]:
print(num, end=' ')
# Output: 0 2 4 6 8
# Reverse loop
for num in numbers[::-1]:
print(num, end=' ')
# Output: 9 8 7 6 5 4 3 2 1 0
# Specific range with step
for num in numbers[1:8:2]:
print(num, end=' ')
# Output: 1 3 5 7
此方法适用于:
- 处理每 n 项
- 反向迭代
- 使用列表的特定部分
实际应用
处理 CSV 数据
以下是处理 CSV 文件中的数据的方法:
# Sample CSV data as list of lists
data = [
['Name', 'Age', 'City'],
['John', '25', 'New York'],
['Alice', '30', 'London'],
['Bob', '35', 'Paris']
]
# Skip header and create user dictionaries
header = data[0]
users = []
for row in data[1:]:
user_dict = {key: value for key, value in zip(header, row)}
users.append(user_dict)
print(users)
# Output: [
# {'Name': 'John', 'Age': '25', 'City': 'New York'},
# {'Name': 'Alice', 'Age': '30', 'City': 'London'},
# {'Name': 'Bob', 'Age': '35', 'City': 'Paris'}
# ]
管理任务队列
具有优先级的处理任务的实际示例:
tasks = [
('High', 'Fix login bug'),
('Low', 'Update documentation'),
('High', 'Deploy new feature'),
('Medium', 'Write tests')
]
# Process high priority tasks first
priorities = ['High', 'Medium', 'Low']
for priority in priorities:
print(f"\n{priority} Priority Tasks:")
for task_priority, task_name in tasks:
if task_priority == priority:
print(f"- {task_name}")
# Output:
# High Priority Tasks:
# - Fix login bug
# - Deploy new feature
#
# Medium Priority Tasks:
# - Write tests
#
# Low Priority Tasks:
# - Update documentation
数据分析
分析销售数据的示例:
sales = [
('Product A', 100, 20.99),
('Product B', 50, 15.99),
('Product C', 75, 10.99),
('Product A', 80, 20.99)
]
# Calculate total sales per product
product_totals = {}
for product, quantity, price in sales:
if product not in product_totals:
product_totals[product] = 0
product_totals[product] += quantity * price
for product, total in product_totals.items():
print(f"{product}: ${total:.2f}")
# Output:
# Product A: $3778.20
# Product B: $799.50
# Product C: $824.25
性能提示
使用大型列表时,请考虑以下有效方法:
large_list = list(range(1000000))
# Memory-efficient filtering with generator expression
def is_even(n): return n % 2 == 0
even_nums = (num for num in large_list if is_even(num))
# Process in chunks
chunk_size = 1000
for i in range(0, len(large_list), chunk_size):
chunk = large_list[i:i + chunk_size]
# Process chunk here
要避免的常见错误
循环时修改列表
# Wrong way - modifies list during iteration
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num) # Don't do this!
# Right way - create a new list or use list comprehension
numbers = [1, 2, 3, 4, 5]
odds = [num for num in numbers if num % 2 != 0]
在必要时使用索引
# Unnecessarily complex
fruits = ['apple', 'banana', 'orange']
for i in range(len(fruits)):
print(fruits[i])
# Cleaner and more pythonic
for fruit in fruits:
print(fruit)
忘记 range() 会排除 end 值
# Might miss the last item
items = ['a', 'b', 'c', 'd']
for i in range(0, len(items) - 1): # Wrong!
print(items[i])
# Correct way
for i in range(len(items)):
print(items[i])
通过了解这些不同的循环方法及其适当的使用案例,您可以编写更高效、可读性更强的 Python 代码。请记住,选择使您的代码最清晰且最适合您的特定情况的方法。