Python Loop Addition

1369
5
Jump to solution
03-31-2017 12:59 PM
MatthewDriscoll
MVP Alum

I am using a search cursor to get some values.  After I would like to add the next total to the total of all the results before it in order.  Not sure what to do, iterate, range, re-loop?

Example:

[a,b,c] would result in [a, a+b, a+b+c]

[3,5,2,3] would result in [3, 8, 10, 13]

value = ""
with arcpy.da.SearchCursor("Feature", "Field") as curs:
 for row in curs:
 value = row[0]

Use the values in "value" to do what I want.

The script will run in ArcGIS Pro.

0 Kudos
1 Solution

Accepted Solutions
DarrenWiens2
MVP Honored Contributor

Use the += operator to accumulate values:

>>> input_list = [3,5,2,3]
... output_list = []
... value = 0
... for i in my_list: # do similar inside your cursor
...     value += i # same as value = value + i
...     output_list.append(value)
... print output_list
... 
[3, 8, 10, 13]‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

View solution in original post

5 Replies
DarrenWiens2
MVP Honored Contributor

Use the += operator to accumulate values:

>>> input_list = [3,5,2,3]
... output_list = []
... value = 0
... for i in my_list: # do similar inside your cursor
...     value += i # same as value = value + i
...     output_list.append(value)
... print output_list
... 
[3, 8, 10, 13]‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
MatthewDriscoll
MVP Alum

Thank you!  I was getting tripped up by my simple mistake of using value = " " instead of value = 0.  

0 Kudos
DanPatterson_Retired
MVP Emeritus

If you are scripting an doing a lot of math, invest some time in learning numpy, a lot of these calculations are builtin

>>> import numpy as np
>>> input_list = [3,5,2,3]
>>> np.cumsum(input_list).tolist()
[3, 8, 10, 13]
>>> 
JoshuaBixby
MVP Esteemed Contributor

Where are you storing the results, in the table the search cursor is iterating over?  If so, you could use an update cursor and do it in place.

Looking just at cumulative totals, the previous responses are all good.  One other option that splits the difference between rolling your own loop and using a 3rd-party library is the accumulate function in itertools (only work in Pro).

>>> from itertools import accumulate
>>> input_list = [3,5,2,3]
>>> list(accumulate(input_list))
[3, 8, 10, 13]
>>>
DanPatterson_Retired
MVP Emeritus

Then someone will want the cumulative sum returned so they can calculate proportions  besides numpy and scipy are builtins in Pro distributions anyway

>>> a = [3,5,2,3]
>>> s = np.sum(a)
>>> cs = np.cumsum(a)
>>> cstand = cs/s
>>> cstand
array([ 0.23076923,  0.61538462,  0.76923077,  1.        ])
>>> ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

or just plain old slicing... but you will need to use a def if you really want to fill values into a table one record at a time.... enough for code golf

[sum(a[:i] ) for i in range( 1, len(a)+1 )]