一文掌握如何在 Python 中遍历列表

liftword4周前 (04-05)技术文章3

列表在 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 代码。请记住,选择使您的代码最清晰且最适合您的特定情况的方法。

相关文章

Python列表操作

Python添加列表4 分钟阅读在 Python 操作列表有各种方法。例如 – 简单地将一个列表的元素附加到 for 循环中另一个列表的尾部,或使用 +/* 运算符、列表推导、extend() 和 i...

Python快速入门教程2:列表

一、列表简介列表(list)是Python中的一种有序且可变的序列类型。它可以存储多个元素,并允许重复元素。列表中的元素可以是不同类型的数据,如整数、字符串、其他列表等。创建列表使用方括号[]创建列表...

每日一练用Python如何输出列表

设置了一个列表,我想输出它,我怎么输出呢?可能很多人感觉我不用到列表,其实就是一个的简单的动作,和我们平常工作一样,经常频繁做一些事情,鼓噪无畏。但还是要学会去弄。当我们列表里面是孩子的成绩,你肯定...

一文掌握如何在 Python 中创建空列表

空列表是许多 Python 程序的起点,无论您是收集用户输入、处理数据还是构建动态数据结构。让我们探索在 Python 中创建和使用空列表的所有方法。创建空列表的基本方法使用方括号创建空列表的最常见和...

在 Python 中将列表写入文件:完整指南

将列表写入文件是 Python 中的一项常见任务,无论您是保存数据以备后用、创建日志还是准备数据供其他程序使用。让我们探索实现此目的的不同方法,并提供您可以立即使用的清晰示例。基本文本文件编写将列表写...

Python之列表(list)

基础概念列表是什么:像一个有序的"容器",可以装多个元素(数字、字符串、列表、字典等),元素用逗号分隔,用 [] 包裹。特点:有序(有下标)、可重复、元素可以修改简单案例# 案例 1:创建一个水果列表...