I have a file GDB that contains Annotation and Polygon feature classes. I would like to create a list of strings with the first part of the name of the polygon features. For example in the data below I would like to create a list that would appear like the following -
['Canal', 'CanalAreas']
I have used ListFeatureClasses in order to get a list of all the polygon classes, but I'm a lot a loss of what the next step is, - a LEN() style function to move the last 6 characters?
lookfor = []
for dataset in arcpy.ListDatasets():
for fc in arcpy.ListFeatureClasses("*", "Polygon", dataset):
lookfor.append(fc)
for fc in arcpy.ListFeatureClasses("*", "Polygon"):
lookfor.append(fc)
I currently have this list hard coded in another script and would like to make it more dynamic so I don't have to worry about data changes etc.
-
1Do you want the part before the first underscore? fcBase = fc.split('_')[0] then if fcBase not in lookfor: lookfor.append(fcBase) - probably best to cast fc = fc.lower() first though to avoid multiple items with slightly different case (CanalAreas is not the same as canalareas). Also consider using arcpy.da.Walk resources.arcgis.com/en/help/main/10.2/018w/… then you won't have to loop for all standalone then all feature classes in feature datasets.Michael Stimson– Michael Stimson2019年05月14日 05:43:48 +00:00Commented May 14, 2019 at 5:43
1 Answer 1
If you always want the part before first underscore then split at this and fetch first item (index 0) in split list. Set will remove duplicates.
import arcpy
arcpy.env.workspace = r'C:\Default.gdb'
polygons = list(set([fc.split('_')[0] for fc in arcpy.ListFeatureClasses(feature_type='POLYGON')]))
You can also use re module to split at first non-letter charachter:
import re
polygons = list(set([re.split('[^a-zA-Z]',fc)[0] for fc in arcpy.ListFeatureClasses(feature_type='POLYGON')]))
-
2Thanks Bera, this looks great. Upon using the code I noticed the first underscore was not always the right one, so I made a small adjustment like so - polygons = list(set([fc[:-6] for fc in arcpy.ListFeatureClasses(feature_type='POLYGON')]))mapface– mapface2019年05月14日 06:20:17 +00:00Commented May 14, 2019 at 6:20