0

I am using a long script for doing this query using select by attribute: this is the following code: are there any shorter form to do this?:

level1 = arcpy.GetParameterAsText(0)
level2 = arcpy.GetParameterAsText(1)
level3 = arcpy.GetParameterAsText(2)
level4 = arcpy.GetParameterAsText(3)
level5 = arcpy.GetParameterAsText(4)
# field's names: L1_NAM,L2_NAM,L3_NAM,L4_NAM,L5_NAM,
query1 = "L1_NAM = '" + level1 + "'"
query2 = "L2_NAM = '" + level2 + "'"
query3 = "L3_NAM = '" + level3 + "'"
query4 = "L4_NAM = '" + level4 + "'"
query5 = "L5_NAM = '" + level5 + "'"

arcpy.SelectLayerByAttribute_management(inputLayer, "NEW_SELECTION",  query1 )
arcpy.SelectLayerByAttribute_management(inputLayer, "SUBSET_SELECTION",  query2 )
arcpy.SelectLayerByAttribute_management(inputLayer, "SUBSET_SELECTION",  query3 )
arcpy.SelectLayerByAttribute_management(inputLayer, "SUBSET_SELECTION",  query4 )
arcpy.SelectLayerByAttribute_management(inputLayer, "SUBSET_SELECTION",  query5 )
1

One shorter form for doing this would be as below. It uses Python string formatting to build a single expression from the five already built.

level1 = arcpy.GetParameterAsText(0)
level2 = arcpy.GetParameterAsText(1)
level3 = arcpy.GetParameterAsText(2)
level4 = arcpy.GetParameterAsText(3)
level5 = arcpy.GetParameterAsText(4)
# field's names: L1_NAM,L2_NAM,L3_NAM,L4_NAM,L5_NAM,
query1 = "L1_NAM = '" + level1 + "'"
query2 = "L2_NAM = '" + level2 + "'"
query3 = "L3_NAM = '" + level3 + "'"
query4 = "L4_NAM = '" + level4 + "'"
query5 = "L5_NAM = '" + level5 + "'"

arcpy.SelectLayerByAttribute_management(inputLayer,"NEW_SELECTION", "{0} AND {1} AND {2} AND {3} AND {4}".format(query1,query2,query3,query4,query5))
  • If the queries were an array, you could use " OR ".join(list) as the where_clause. – Vince Jul 24 at 10:53

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.