I have a long record of data in a list format which I want to separate that record according to a certain condition. I want to get the sum of the list elements so the sum order will stop when consecutive 3 or more elements are equal to 0, then the sum order restarts again from where it stopped.
for ex: part of the list is [8, 2, 1, 1, 2, 0, 0, 0, 0, 0, 6, 0, 2, 0, 0, 0, 6, 0]
the output should be a new list of [14, 8, 6] where: output1: 8 + 2 + 1 + 1 + 2 = 14, output2: 6 + 2 = 8, and output3: 6
I write so far something like below but I have two problems: 1- list index out of range, 2- the fake list extension with three 0 elements at the end of the list
# note: i add three fake 0 at the end of the list to get the correct output
arr = [8, 2, 1, 1, 2, 0, 0, 0, 0, 0, 6, 0, 2, 0, 0, 0, 6, 0, 0, 0, 0]
result = []
cum = 0
for i in range(0, len(arr)):
el, el1, el2 = arr[i], arr[i+1], arr[i+2]
if el != 0:
cum = cum + el
if el == 0 and el1 == 0 and el2 == 0:
if cum != 0:
result.append(cum)
cum = 0
This will solve both your problems:
arr = [8, 2, 1, 1, 2, 0, 0, 0, 0, 0, 6, 0, 2, 0, 0, 0, 6, 0]
result = []
cum = 0
for i in range(0, len(arr) - 2):
el, el1, el2 = arr[i], arr[i + 1], arr[i + 2]
if el != 0:
cum = cum + el
if el == 0 and el1 == 0 and el2 == 0:
if cum != 0:
result.append(cum)
cum = 0
elif i == len(arr) - 3:
cum = el + el1 + el2
result.append(cum)
break
print(result)
The 'elif i == len(arr) - 3:' condition makes sure that your loop breaks when you have reached last 3 elements. Additionally it will execute only when at least 1 element is non-zero from last three.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments