能否用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
kin the resultingreslist (from 0 tolen(x)+len(h)-2). - For each
k, we use a generator expression to find all valid indicesiinxsuch that the correspondingj = k - iis a valid index inh(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 ofres[k]—exactly what your nested loops do, just in a more declarative way.
Additional Notes
- If your
reswasn’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

