0

in Arcpy trying to create a subset of rasters from a list of rasters.

Basically the idea, run arcpy.ListRasters on a geodatabase, check all raster names for a user input value, then add those rasters that match to a new list. ideally, the user would be able to add the values they want as a list of values and the code iterates through each one. And actually I'm trying to get it so it will refine the new list further. but I only really need the code to do the first one.

Code so far

 listvals = arcpy.GetParameterAsText(0)
 listrasters = arcpy.ListRasters
 for raster in listrasters:
    rastname = str(raster)
    for val in listvals
       a = rastname.rfind(val,7,10)
       if a > 0:
          #add raster to newlist
       else:
          #do nothing
  • Are you just interested in how to create and modify a collection in Python? – AHigh Feb 22 '17 at 23:45
  • What happens when you run this code? What gets printed when you make print listrasters your second line of code? Have you configured a tool dialog? – PolyGeo Feb 22 '17 at 23:45
  • @AHigh That sounds exactly like what I'm trying to do. – Lists Feb 22 '17 at 23:46
  • @PolyGeo It returns the ListRaster function. <function ListRasters at 0x19AA96B0>. but this portion of code I know works to iterate through the rasters in the workspace (for my purposes a geodatabase). Yes I've got a tool dialog. – Lists Feb 22 '17 at 23:50
  • 1
    Your code will fail on lines 3 and 5 as For should be lowercase for – Midavalo Feb 22 '17 at 23:53
1

You should be able to just initialize an empty list and then append the raster to it if it matches your criteria. See below. I've also removed the unused else block and cleaned up some syntax issues.

listvals = arcpy.GetParameterAsText(0)
listrasters = arcpy.ListRasters

#Initialize an empty list
matchedRasters = []

for raster in listrasters:
        rastname = str(raster)
        for val in listvals:
           a = rastname.rfind(val,7,10)
           if a > 0:
              #add raster to newlist
              matchedRasters.append(raster)

Here's some material on collections and lists in Python that you may find useful: https://docs.python.org/3/tutorial/datastructures.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.