Hello, I'm a beginner who's having a hard time just after entering Python.
What I'm curious about is the application of the cusum function to the list.
list1 = [2, 2, 3, 3, 3, 1, 4, 4, 4, 4, 2, 2]
If there's a list like this, I want to cumsum with values excluding duplicate values.
The result value I want is
list1_result = [2, 2, 5, 5, 5, 6, 10, 10, 10, 10, 12, 12]
I want to get these list result values.
Thank you for your help.
python
list1 = [2, 2, 3, 3, 3, 1, 4, 4, 4, 4, 2, 2]
cumsum = []
prev = 0
for i, e in enumerate(list1):
if i == 0:
cumsum.append(e) # The initial sum is the first element.
elif prev == e:
cumsum.append(cumsum[-1]) # Use the last sum again if it is the same as the previous one.
else:
cumsum.append(cumsum[-1]+e) # Add this element to the last sum.
prev = e
print(cumsum)
list1 = [2, 2, 3, 3, 3, 1, 4, 4, 4, 4, 2, 2]
import itertools as it
list(it.chain(*it.accumulate([list(v) for _, v in it.groupby(list1)], lambda a, b:[a[0] + i for i in b])))
[2, 2, 5, 5, 5, 6, 10, 10, 10, 10, 12, 12]
© 2024 OneMinuteCode. All rights reserved.