簡體   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