This is a question related to Python list cusum.

Asked 2 years ago, Updated 2 years ago, 13 views

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

2022-09-20 17:43

2 Answers

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)


2022-09-20 17:43

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]


2022-09-20 17:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.