You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含变量赋值的嵌套循环转换为Python列表推导式

Converting Nested Accumulator Loop to List Comprehension

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 e in list C, you initialize a total t=0, then iterate over every tuple r in D. Whenever r[0] matches e, you add r[2] to t. Finally, you append the tuple (e, t) to list L.

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 C mirrors your original outer loop, iterating over each element in C.
  • Instead of manually initializing t and adding to it, we use sum() with a generator expression: r[2] for r in D if r[0] == e. This generator yields every r[2] value where r[0] equals e, and sum() automatically accumulates those values into the total we need.
  • We wrap each e and its corresponding sum into a tuple (e, ...), just like your original L.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:54:20