All my python knowledge has left me alone and afraid after ignoring it for over a year (and not having that much of it to start with).
I have the following script that will create a running total of a list of numbers. It works swell on lists, but I need it to work on sub-lists. How do I modify to accommodate?
list = IN[0]
mass = 0
masspart = []
if hasattr(list, "__iter__"):
for i in range(0,len(list)):
mass = mass + list[i]
masspart.append(mass)
else:
masspart.append(list)
OUT = masspart
first of all there is a small mistake in this code that the lines under for needed to be indented. like this
list = IN[0]
mass = 0
masspart = []
if hasattr(list, "__iter__"):
for i in range(0,len(list)):
mass = mass + list[i]
masspart.append(mass)
else:
masspart.append(list)
OUT = masspart
and the idea of irritating through sub lists by make a loop inside a loop
list1=IN[0]
total2 =0
total1=[]
for i in list1:
for j in i:
total2=total2+j
total1.append(total2)
#Assign your output to the OUT variable.
OUT = total11

2 Likes
Thanks, But I actually need the running total not just the sum. e.g. for the output from your example List0 would be 1,3,6,10,15 and List1 would be 6,13,21,30,40.
Create a variable to store your running total which gets reset every outer loop. Modifying kuzaimah’s code above:
list1 = IN[0]
totals = []
for i in list1:
running_total = 0
subtotals = []
for j in i:
running_total += j
totals.append(subtotals)
#Assign your output to the OUT variable.
OUT = totals
Your code works for a single list. You need to add an additional for
loop and move some of your variables so they reset.
lists = IN[0]
out = []
for list in lists:
masspart = []
mass = 0
if hasattr(list, "__iter__"):
for i in range(0,len(list)):
mass = mass + list[i]
masspart.append(mass)
else:
masspart.append(list)
out.append(masspart)
OUT = out
1 Like
in my example by adding extra list to store each value in it (total3), and store the whole list as a sublist in the main list (total1), notice that we have to clear the values inside the (total3 ) in each iteration through the sublist, so we defining it after the first iteration
list1=IN[0]
total2 =0
total1=[]
total3=[]
for i in list1:
total3=[]
for j in i:
total2=total2+j
total3.append(total2)
total1.append(total3)
#Assign your output to the OUT variable.
OUT = total1