Python3 推导式

列表、字典、集合推导式与生成器表达式的写法、嵌套与性能取舍。

Intermediate
Key Points推导式用一行完成「遍历 + 过滤 + 变换」;生成器表达式用 () 惰性求值,省内存。

列表推导式

Syntax: [expr for var in iterable if cond], allowing several for clauses and conditions. It is faster than a manual loop and reads as "what I want" instead of "how to build it".

Python
print([x ** 2 for x in range(5)])
print([x for x in range(10) if x % 2 == 0])
print([x if x > 0 else 0 for x in (-2, 3, -1, 4)])

print([(x, y) for x in range(2) for y in range(2)])
print([[x * y for y in range(3)] for x in range(2)])
Output
[0, 1, 4, 9, 16]
[0, 2, 4, 6, 8]
[0, 3, 0, 4]
[(0, 0), (0, 1), (1, 0), (1, 1)]
[[0, 0, 0], [0, 1, 2]]

字典推导式

Build dicts with {key_expr: value_expr for ...}. Typical uses: swapping keys and values, renaming keys by rule, or zipping two sequences.

Python
print({x: x ** 2 for x in range(4)})
print({v: k for k, v in {'a': 1, 'b': 2}.items()})
print({k: v for k, v in {'a': 1, 'b': 2}.items() if v > 1})
print(dict(zip(['x', 'y'], [1, 2])))
Output
{0: 0, 1: 1, 2: 4, 3: 9}
{1: 'a', 2: 'b'}
{'b': 2}
{'x': 1, 'y': 2}

集合推导式

A set comprehension uses {expr for ...} and deduplicates automatically. Note {} is an empty dict; write set() for an empty set.

Python
print({x % 3 for x in range(10)})
print(sorted({c.lower() for c in 'AbcABC'}))
print(len({x // 2 for x in range(10)}))
Output
{0, 1, 2}
['a', 'b', 'c']
5

元组推导式(生成器表达式)

There is no tuple comprehension — parentheses produce a generator expression, lazily evaluated, single-pass, with constant memory. Wrap in tuple() when you really need a tuple.

Python
g = (x ** 2 for x in range(5))
print(type(g).__name__)
print(sum(g))
print(sum(g))

print(tuple(x for x in range(3)))
print(max(x for x in range(5)))
Output
generator
30
0
(0, 1, 2)
4
A generator is single-use: the second sum(g) returns 0 because the iterator is exhausted. Store a list if you need to iterate more than once.

Friends & Partners