对列表执行数学运算(递归还是非递归?)

2024-04-20 09:17:43 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我们有以下列表

lst = [3,6,1,4]

我想从这个列表中得到以下结果

result = [4, 10, 11, 15]

计算模式如下:

1+3=4

1+3+6=10

1+3+6+1=11

1+3+6+1+4=15

换句话说,结果是1加上输入数组的累积和。你知道吗

如何定义一个函数来解决这个问题?你知道吗


Tags: 函数列表定义模式数组resultlst
3条回答
[sum(lst[:i+1])+1 for i in range(len(lst))]

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

下面是我们正在做的,以及here's the docs on 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.

请注意,您也可以使用相同的格式来生成表达式,但是用()而不是[]来封装它们,并且可以使用{key:value for key,value in iterable}来进行字典理解

这可能比列表理解更容易理解:

result = []
total = 1 
lst = [3,6,1,4]

for value in lst:
     total += value
     result.append(total)

print result

如果模式是累积和+1,则应该这样做。使用一个基本的生成器和解决方案是相当简单和有效的。你知道吗

def csum(mylist, c=1):
    total = c
    for i in mylist:
        total += i
        yield total 

lst = [3,6,1,4]

print list(csum(lst))

output : [4, 10, 11, 15]

相关问题 更多 >