繁体   English   中英

将前一个元素添加到列表中的当前元素然后分配给变量 - Python 3.5.2

[英]Add previous element to current in list then assign to variable - Python 3.5.2

在这里的第一篇文章,我被激怒了! 好的,所以问题是:如何将以前的元素添加到当前元素,然后从这些值中创建一个新列表以将它们添加到matplotlib图形中? 这是我的代码示例:


example_list = [20, 5, 5, -10]

print(example_list) '''first output should be'''
[20, 5, 5, -10]

value1 = (example_list[0])
value2 = (example_list[0] + example_list[1])
value3 = (example_list[0] + example_list[1] + example_list[2])
value4 = (example_list[0] + example_list[1] + example_list[2] + example_list[3])

'''我认为你可以看到我想要做的''''

del example_list [:]

example_list.append(value1)
example_list.append(value2)
example_list.append(value3)
example_list.append(value4)

print(example_list)
'''output should be:'''

[20, 25, 30, 20]

'''这适用于硬编码,但我希望这可以发生在数百个元素上。 (当人们从我的“simple_finance_app”Python脚本添加到列表中时)'''感谢您的帮助! (PS我已经有了matplotlib代码所以不需要添加它,但是,我可以帮助其他人阅读这个问题/答案)

您可以使用itertools.accumulate方法:

from itertools import accumulate from operator import add

result = list(accumulate(example_list,add))

这会产生:

>>> list(accumulate(example_list,add))
[20, 25, 30, 20]

如果函数(此处为operator.add )在O(n)中工作 ,则accumulate将在O(n)中工作,而您的硬编码解决方案在O(n 2 )中工作

基本上, accumulate(iterable[,func])函数将可迭代的[x1,x2,...,xn]和函数f作为输入,并且每次迭代它在累加器和新元素上调用f 在第一步中,它发出第一个元素,然后累加器成为该元素。 所以它基本上生成[x1,f(x1,x2),f(f(x1,x2),x3),...] 但是, 如果没有计算f(x1.x2)各一次。 因此,它在语义上等同于:

def accumulate(iterable,func): # semantical equivalent of itertools.accumulate
    iterer = iter(iterable)
    try:
        accum = next(iterer)
        while True:
            yield accum
            accum = func(accum,next(iterer))
    except StopIteration:
        pass

但可能更不容易出错,效率更高。

你的意思是sum与切片相结合?

li = [1, 2, 3, 4]

a = sum(li[:1])
b = sum(li[:2])
c = sum(li[:3])
d = sum(li[:4])  # same as sum(li) in this case

或者一般来说:

li = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for i in range(len(li)):
    print(sum(li[:i + 1]))
# 1
# 3
# 6
# 10
# 15
# 21
# 28
# 36
# 45

香草for循环的解决方案:

>>> example_list = [20, 5, 5, -10]
>>> out = []
>>> sum = 0
>>> for x in example_list:
...     sum += x
...     out.append(sum)
... 
>>> out
[20, 25, 30, 20]

注意,在for循环/理解中重复调用sum将导致O(n ^ 2)复杂度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM