将单调递增的序列列表累积到线性列表

时间:2019-06-14 10:42:16

标签: python-2.7

嗨,我是python和一般编程人员的新手。 我有一个单调的清单,例如。 L = [1,2,3,4,0,1,2,3,4,5,0,1,2,3,4,0,1...] 每当序列达到0时,我都希望采用先前的值并将其添加到列表的其余部分,以使列表变为线性。

L_sequence = [1,2,3,4,0,1,2,3,4,5,0,1,2,3,4,0,1...]
L_linear = [1,2,3,4,4,5,6,7,8,9,9,10,11,12,13,13,14...]

我知道这样做很讨厌,但是如果您有一个好的解决方案,欢迎您与我们分享。

1 个答案:

答案 0 :(得分:0)

我认为它应该可以解决您的问题:

l = [1,2,3,4,0,1,2,3,4,5,0,1,2,3,4,0,1]
x = []
helperOne = 0
helperTwo = 0 
goForIt = False
for i in l:
    if i == 0:
        goForIt = True
        helperTwo = helperOne + helperTwo 

    if goForIt==True: 
        t = helperTwo + i
        x.append(t)

    else:
        x.append(i)
    helperOne = i  

print x

输出:

[1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 9, 10, 11, 12, 13, 13, 14]