首页 > 解决方案 > 重写代码以使用列表推导对初始列表中的值求和

问题描述

我写了这段代码:

rand_map, lst = [2, 2, 6, 6, 8, 11, 4], []

for i in range(len(rand_map)):

    num = rand_map[i]
    lst.append(num)

    for j in range(i+1, len(rand_map)):
        assembly = num + rand_map[j]
        num += rand_map[j]
        lst.append(assembly)
print(sorted(lst))

这给出了这个输出:

[2, 2, 4, 4, 6, 6, 8, 8, 10, 11, 12, 14, 14, 15, 16, 19, 20, 22, 23, 24, 25, 29, 31, 33, 35, 35, 37, 39]

我一直在尝试使用列表推导重写此代码,但我不知道如何。我尝试了多种方法(标准和 itertools),但我就是做错了。我将非常感谢您的帮助!

标签: pythonlistfor-looplist-comprehensionaddition

解决方案


我想出了几个解决这个问题的方法:

方法 1 - 香草列表理解

在这种方法中,我们迭代两个变量,ij计算sum这两个索引之间的元素。

代码:

>>> rand_map = [2, 2, 6, 6, 8, 11, 4]
>>> sorted([sum(rand_map[i:i+j+1]) for i in range(len(rand_map)) for j in range(len(rand_map)-i)])
[2, 2, 4, 4, 6, 6, 8, 8, 10, 11, 12, 14, 14, 15, 16, 19, 20, 22, 23, 24, 25, 29, 31, 33, 35, 35, 37, 39]

方法 2 - Itertools

In this approach, we use the itertools recipe from here to iterate n-wise through the rand_map list, and calculate the sums accordingly. This works in approximately the same way as the first approach, but is a bit tider.

Code:

from itertools import islice

def n_wise(iterable, n):
    return zip(*(islice(iterable, i, None) for i in range(n)))

print(sorted([sum(x) for n in range(len(rand_map)) for x in n_wise(rand_map, n+1)]))

Output:

[2, 2, 4, 4, 6, 6, 8, 8, 10, 11, 12, 14, 14, 15, 16, 19, 20, 22, 23, 24, 25, 29, 31, 33, 35, 35, 37, 39]

推荐阅读