3

I want to use a loop to select values with expression in a layer. The values contain the letters OS and a number (example: "OS1","OS2"). I want to use the loop to increase the number to use my processing script on the features separately. How do I use the selectbyexpression() in the right way to increase the number in a loop?

i = 1
OSnumber = str(i)
OSname = 'OS'+OSnumber

OS_trace = Map+'OS_tracés.shp'
layer = iface.activeLayer()
layer.selectByExpression("attributename = 'Osname'")

1 Answer 1

7

You can use the following script structure:

layer = iface.activeLayer()

end_number = 5 # OS1, OS2, OS3, OS4, OS5
attribute_name = "attribute_name" # field name containing OS values

for i in range(end_number):
    osname = f"OS{i+1}"
    layer.selectByExpression(f"{attribute_name} = '{osname}'")

    # Do whatever with the selected features
    # For example:
    print(layer.selectedFeatureCount())

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.