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

能否用Python列表推导式实现该含累加操作的双重循环代码?

Absolutely! You can rewrite this nested loop logic with a Python list comprehension—though we’ll need to reframe the way we calculate each element of res instead of modifying an existing list in-place.

First, let’s clarify what your original code does: it’s computing the discrete convolution of two sequences (or equivalently, calculating coefficients for polynomial multiplication). You initialize res as a zero-filled list, then accumulate products x[i] * h[j] into the position i+j of res.

The List Comprehension Approach

Instead of iterating over i and j to update res in-place, we can generate each element of res directly by summing all valid x[i] * h[j] pairs that map to the same position k = i+j.

Example Implementation

Suppose your original code looks like this:

x = [1, 2, 3]
h = [4, 5]
res_length = len(x) + len(h) - 1
res = [0] * res_length

# Your original nested loops
for i in range(len(x)):
    for j in range(len(h)):
        res[i + j] += x[i] * h[j]

The equivalent list comprehension would be:

res = [
    sum(x[i] * h[k - i] for i in range(len(x)) if 0 <= k - i < len(h))
    for k in range(len(x) + len(h) - 1)
]

Breakdown of the Logic

  • The outer list comprehension iterates over every position k in the resulting res list (from 0 to len(x)+len(h)-2).
  • For each k, we use a generator expression to find all valid indices i in x such that the corresponding j = k - i is a valid index in h (i.e., 0 <= j < len(h)).
  • We calculate the product x[i] * h[j] for each valid pair, then sum those products to get the value of res[k]—exactly what your nested loops do, just in a more declarative way.

Additional Notes

  • If your res wasn’t initialized to zero but had pre-existing values, you can easily adjust the list comprehension to add the convolution sum to the initial values:
    initial_res = [10, 20, 30, 40]
    res = [
        initial_res[k] + sum(x[i] * h[k - i] for i in range(len(x)) if 0 <= k - i < len(h))
        for k in range(len(initial_res))
    ]
    
  • For most use cases, this list comprehension is more Pythonic and readable than nested loops. That said, if you’re working with extremely large arrays, the original in-place loop might have a tiny memory advantage—but the difference is negligible for most everyday tasks.

内容的提问来源于stack exchange,提问作者Abdullah Alattar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:23:41