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]
833 Error in x, y, and format string must not be None
915 Uncaught (inpromise) Error on Electron: An object could not be cloned
796 GDB gets version error when attempting to debug with the Presense SDK (IDE)
845 M2 Mac fails to install rbenv install 3.1.3 due to errors
1338 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2025 OneMinuteCode. All rights reserved.