在列表上执行数学运算(是否递归?)

Kri*_*Pal 0 python recursion list python-2.7

假设我们有以下列表

lst = [3,6,1,4]
Run Code Online (Sandbox Code Playgroud)

我希望能够从此列表中获得以下结果

result = [4, 10, 11, 15]
Run Code Online (Sandbox Code Playgroud)

计算模式如下:

1 + 3 = 4

1 + 3 + 6 = 10

1 + 3 + 6 + 1 = 11

1 + 3 + 6 + 1 + 4 = 15

换句话说,结果是1加上输入数组的累加和。

如何定义一种可以解决此问题的功能?

Ada*_*ith 5

[sum(lst[:i+1])+1 for i in range(len(lst))]
Run Code Online (Sandbox Code Playgroud)

最终列表中的每个元素都是原始列表中一个以上连续元素的总和,对吗?列表理解能力擅长从可迭代对象构建列表:)

这是我们正在做的事情,这是list comps上的文档

[sum(lst[:i+1])+1 for i in range(len(lst))]
 ^^^^^^^^^^^^^^^^
# This element is the sum+1 of the slice starting at lst[0] and ending at i,

[sum(lst[:i+1])+1 for i in range(len(lst))]
                  ^^^^^^^^^^^^^^^^^^^^^^^^
# Do this for one element each for every i in range(len(lst))

[sum(lst[:i+1])+1 for i in range(len(lst))]
^                                         ^
# And give me the results as a list.
Run Code Online (Sandbox Code Playgroud)

请注意,您还可以使用相同的格式来生成生成器表达式,但用()而不是将其括起来[],并且可以使用来进行字典解析{key:value for key,value in iterable}

  • @adsmith Id只是想补充一点,尽管这是可读性很强的代码,但是它效率也很低,因为您正在计算那里每个子列表的总和。 (2认同)