如何将含变量赋值的嵌套循环转换为Python列表推导式
Great question! Converting loops with accumulator variables (like your t here) to list comprehensions can feel a bit counterintuitive at first, but once you leverage Python's built-in functions, it becomes straightforward.
First, let's recap what your original code does:
For each element
ein listC, you initialize a totalt=0, then iterate over every tuplerinD. Wheneverr[0]matchese, you addr[2]tot. Finally, you append the tuple(e, t)to listL.
The List Comprehension Solution
Here's how to rewrite this logic cleanly using a list comprehension combined with a generator expression inside sum():
L = [(e, sum(r[2] for r in D if r[0] == e)) for e in C]
Let's break down how this works:
- The outer
for e in Cmirrors your original outer loop, iterating over each element inC. - Instead of manually initializing
tand adding to it, we usesum()with a generator expression:r[2] for r in D if r[0] == e. This generator yields everyr[2]value wherer[0]equalse, andsum()automatically accumulates those values into the total we need. - We wrap each
eand its corresponding sum into a tuple(e, ...), just like your originalL.append((e, t))does.
Bonus: Optimizing for Large Datasets
If D is large and C has many elements, the above solution will iterate over D once per element in C—which can be slow. For better performance, pre-process D into a dictionary first to map each key r[0] to the sum of its r[2] values:
from collections import defaultdict # Precompute sums for all keys in D sum_map = defaultdict(int) for r in D: sum_map[r[0]] += r[2] # Build L in a single pass over C L = [(e, sum_map[e]) for e in C]
This way, we only iterate over D once, making the solution much more efficient for large datasets.
内容的提问来源于stack exchange,提问作者Iltl

