I've been looking extensively to find a solution for what I think is a very simple exercise.
In general, I would like to know how I can extract a variable from a loop in Python and then use it elsewhere in the script. I've limited Python knowledge, however I know from R
that this should be fairly simple. More specifically, my case is explained below.
I've two loops both multiplying rasters. I need to extract variables from each of the loops and then add them together.
import arcpy, os
from arcpy import env
from arcpy.sa import *
arcpy.CheckOutExtension("spatial")
arcpy.env.overwriteOutput = True
env.workspace = "D:/Join"
#
outputFolder = env.workspace
#
# A list of two different rasters
wheat = ["a_wheat", "b_wheat"]
for w in wheat:
r_w=Times("landuse_w",w) # landuse is a raster
r_w.save(os.path.join(outputFolder, "r_" + w ))
# This will generate r_a_wheat, r_b_wheat
barl = ["a_barl", "b_barl"]
for b in barl:
r_b=Times("landuse_b",b)# landuse is a raster
r_b.save(os.path.join(outputFolder, "r_" + b))
# This will generate r_a_barl, r_b_barl
#
# Add rasters
add_a = r_a_wheat + r_a_barl
add_b = r_b_wheat + r_b_barl
The problem with the loops like this is that I need to save everything and then add up. I would prefer to extract from r_w
the two rasters (r_a_wheat, r_b_wheat
), do the same for r_b
and then add up without having to save files. Is that possible?
-
With so few layers to process why go to the effort and add them to a list and cycle through those when you could simply reference them individually?Hornbydd– Hornbydd2018年01月10日 21:30:43 +00:00Commented Jan 10, 2018 at 21:30
-
I have 10 layers for each loop. I gave this as an example.egi007– egi0072018年01月10日 22:19:46 +00:00Commented Jan 10, 2018 at 22:19
-
You should always explain the whole situation ;)Hornbydd– Hornbydd2018年01月10日 22:45:29 +00:00Commented Jan 10, 2018 at 22:45
1 Answer 1
Now that you have described your problem in a bit more detail, why not cycle through the lists using their index number 0 to 9 pulling out the names, as it appears that you are pairing them.
Pseudo code:
wheat = ["a_wheat", "b_wheat","c_wheat"]
barl = ["a_barl", "b_barl","c_barl"]
for i in range(0,3,1):
ras1 = wheat[i]
ras2 = barl[i]
print "processing " + ras1 + " & " + ras2
r_w=Times("landuse_w",ras1)
r_b=Times("landuse_b",ras2)
add = r_w + r_b
add.save("yourrastername")
-
Thanks @Hornbydd! I don't want to add all rasters at the end. I need
add_a = r_w_a + r_b_a
;add_b = r_w_b + r_b_b
;add_c = r_w_c + r_b_c
That's why I thought of extracting the elements from loops and using them to add at the end.egi007– egi0072018年01月12日 15:24:43 +00:00Commented Jan 12, 2018 at 15:24