With PyQGIS I would like to use several "ID"
s (in a list) to select certain objects in order to make them available later in a temporary layer. I know how to select one or a few more objects, but my list can contain a large number of "ID"
s. My attempt to run
for x in list:
layer.selectByExpression("id = '{}'".format(x))
in a for
loop did not work. How can I select multiple features in a data set?
3 Answers 3
Use this way (without for
loop):
id_list = [1, 2, 5]
layer.selectByExpression("id in {}".format(tuple(id_list)))
You can also:
layer = QgsProject.instance().mapLayersByName('mylayer')[0]
layer.removeSelection()
mylist = [0,2,4]
layer.select([f.id() for f in layer.getFeatures() if f['id'] in mylist])
You can simply do:
id_list = [4, 5, 7, 11, 14]
layer.selectByIds(id_list)
And, for the sake of interest, I think that a slight variation of your original for loop would work fine if you pass an additional argument to specify the select behavior as QgsVectorLayer.AddToSelection
(the default is QgsVectorLayer.SetSelection
). If you are working with feature ids, you would use the variable '$id' in your expression:
id_list = [4, 5, 7, 11, 14]
for i in id_list:
layer.selectByExpression("$id = {}".format(i), QgsVectorLayer.AddToSelection)
On the other hand, if you are matching integers in your list to an attribute field called "id", you could use the following expression:
id_list = [4, 5, 7, 11, 14]
for i in id_list:
layer.selectByExpression("\"id\" = {}".format(i), QgsVectorLayer.AddToSelection)
By the way, using the word 'list' as a variable name is not recommended and can cause unexpected behavior- 'list' is a built in class in Python. If you just run:
print(list)
in the Python console, you get an output like:
<class 'list'>
-
2@MrXsquared, your comment was thought provoking to me and led me to improve my answer (I think)- so thank you! Yes, the first solution refers to feature ids, but I have edited my answer to cover both cases for the second- since, after re-reading the OP's question, it is not clear to me which one they are actually using.Ben W– Ben W2021年08月31日 11:52:46 +00:00Commented Aug 31, 2021 at 11:52
Explore related questions
See similar questions with these tags.