Skip to content

列表 Comprehensions

编写 concise, readable 列表 transformations 使用 comprehensions, 筛选, and nested 循环.

你将学到

  • 编写基础列表 comprehensions
  • 添加 conditional 筛选到 comprehensions
  • Use nested comprehensions for 2D 数据
  • Apply dict and 设置 comprehensions
  • Know 当 comprehensions help 对比 hurt readability

概念讲解

Basic Syntax

A list comprehension creates a new list by applying an expression to each item in an iterable. It replaces the verbose for-loop + append pattern:

# Old way — verbose
squares = []
for x in range(10):
    squares.append(x ** 2)

# Comprehension — concise and readable
squares = [x ** 2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The general form is: [表达式 for 项 in iterable]. Read it left-to-right: "give me 表达式, for 每个项 in iterable." Comprehensions are both faster (optimized internally) and more readable than the equivalent loop.

Conditional Filters

Add an 如果 clause to filter which items are included:

# Even numbers only
evens = [x for x in range(20) if x % 2 == 0]

# Strings longer than 3 characters
words = ["cat", "house", "dog", "elephant", "bee"]
long_words = [w for w in words if len(w) > 3]
# ['house', 'elephant']

The filter goes after the for clause. Only items where the condition is True are included in the result.

Conditional Expression (Ternary)

Use an 如果/else inside the expression to transform values conditionally:

# Label numbers as even or odd
labels = ["偶数" if x % 2 == 0 else "奇数" for x in range(5)]
# ['even', 'odd', 'even', 'odd', 'even']

# Replace negatives with 0
numbers = [1, -2, 3, -4, 5]
clamped = [x if x >= 0 else 0 for x in numbers]
# [1, 0, 3, 0, 5]

Note the position: [expr_if_true 如果 条件 else expr_if_false for 项 in iterable]. This is different from the filter — the ternary transforms every item, while the filter excludes items.

Nested Comprehensions

You can nest loops for multi-dimensional data:

# Flatten a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Create a 3x3 identity matrix
identity = [[1 if i == j else 0 for j in range(3)] for i in range(3)]
# [[1, 0, 0], [0, 1, 0], [0, 0, 1]]

Read nested comprehensions from left to right, outer loop first. They can get hard to read — if you need more than two levels, use a regular loop for clarity.

Dict Comprehensions

# Square each number as a key-value pair
squares = {x: x ** 2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Invert a dictionary (swap keys and values)
original = {"": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
# {1: 'a', 2: 'b', 3: 'c'}

# Filter dict items
prices = {"apple": 1.5, "banana": 0.5, "cherry": 3.0}
expensive = {k: v for k, v in prices.items() if v > 1.0}
# {'apple': 1.5, 'cherry': 3.0}

Set Comprehensions

# Unique lengths of words
words = ["cat", "dog", "house", "bee", "树"]
unique_lengths = {len(w) for w in words}
# {3, 4, 5} — a set, duplicates removed

Use curly braces {} for set comprehensions and {k: v ...} for dict comprehensions.

Generator Expressions

Replace the square brackets with parentheses to create a generator — it produces items lazily, one at a time, saving memory:

# List comprehension — all values in memory at once
squares_list = [x ** 2 for x in range(1000000)]

# Generator expression — produces values on demand
squares_gen = (x ** 2 for x in range(1000000))
print(sum(squares_gen))  # computes without storing all values

Generators are ideal for large datasets and pipelines where you do not need all values simultaneously.

When NOT to Use Comprehensions

Comprehensions are great, but they can hurt readability when:

  • The expression is complex or has multiple function calls
  • You need more than two nested loops
  • You need side effects (comprehensions should be pure)
# Too complex — use a regular loop
# result = [transform(x) for x in data if validate(x) and not skip(x) and x.priority > 5]

# Better:
result = []
for x in data:
    if not validate(x) or skip(x):
        continue
    if x.priority <= 5:
        continue
    result.append(transform(x))

Rule of thumb: if you cannot read it in one glance, use a regular for loop.

示例代码

              # Basic comprehension
squares = [x ** 2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# Conditional filter
evens = [x for x in range(20) if x % 2 == 0]
print(evens)  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# Ternary expression
labels = ["even" if x % 2 == 0 else "odd" for x in range(5)]
print(labels)  # ['even', 'odd', 'even', 'odd', 'even']

# String filtering
words = ["cat", "house", "dog", "elephant", "bee"]
long_words = [w.upper() for w in words if len(w) > 3]
print(long_words)  # ['HOUSE', 'ELEPHANT']

# Flatten a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Dict comprehension — invert a dict
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted)  # {1: 'a', 2: 'b', 3: 'c'}

# Set comprehension — unique lengths
word_list = ["cat", "dog", "house", "bee", "tree"]
unique_lengths = {len(w) for w in word_list}
print(unique_lengths)  # {3, 4, 5}

# Generator expression — memory efficient
total = sum(x ** 2 for x in range(100))
print(f"Sum of squares 0-99: {total}")

# Practical: extract emails from user dicts
users = [
    {"name": "Ada", "email": "[email protected]", "active": True},
    {"name": "Bob", "email": "[email protected]", "active": False},
    {"name": "Cy", "email": "[email protected]", "active": True},
]
active_emails = [u["email"] for u in users if u["active"]]
print(active_emails)  # ['[email protected]', '[email protected]']
            

Demonstrates 基础 comprehensions, conditional 筛选, ternary 表达式, 字符串处理, flattening 2D 列表, dict inversion, 设置 deduplication, generator 表达式使用总和(), and practical 真实-世界示例 extracting active 用户 emails.

动手试一试

  • 文本计数器

    Comprehensions 是 perfect for transforming counted 文本数据.

  • JSON Formatter

    Dict comprehensions transform JSON-如数据结构.

常见错误

错误写法

制作 comprehensions 也复杂到 读取 in one glance

正确做法

如果 comprehension 有多个条件, nested 循环, or 复杂表达式, 它 hurts readability. Rewrite as regular for 循环. 规则: 如果你 cannot 读取它 at glance, use 循环. Readability beats cleverness (PEP 8).

错误写法

Using 列表 comprehension 当 generator 表达式会 保存 memory

正确做法

[expr for x in 数据] 创建整个列表 in memory. (expr for x in 数据) 创建 generator 那个 yields 项 lazily. For 大数据处理 in 流水线 (e.g., 总和()), use generator 表达式到 avoid 存储所有值.

相关速查表

练习 列表 Comprehensions

3 个练习

练习 列表 Comprehensions

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误