1

I am trying to go through a for loop in QGIS's Python module in reverse order for my features.

from qgis.utils import iface
from PyQt4.QtCore import *
layers = iface.legendInterface().layers()
for layer in layers:
    name = layer.name()
    myLayer = QgsMapLayerRegistry.instance().mapLayersByName( name )[0]
    if name.startswith('Test'):
        for f in layer.getFeatures():

I would like to be able to go through that second for loop in reverse order. I know python has the reversed() function but that is only for lists. I can't seem to use it for layer.getFeatures().

Is there a way to do this?

2
  • 2
    Perhaps you could do something like "features = sorted(layer.getFeatures(), key=get_name)" as shown over here by walkermatt: gis.stackexchange.com/questions/138769/…
    – cm1
    May 31 '18 at 20:43
  • This will work for what I need! Thanks for pointing this out
    – efrank
    May 31 '18 at 22:03
2

getFeatures() by itself would return the features in an unpredictable order, so taking the reverse order is also unpredictable.

You can specify a QgsFeatureRequest containing an order by clause

from qgis.utils import iface
from PyQt4.QtCore import *
layers = iface.legendInterface().layers()
for layer in layers:
    name = layer.name()
    myLayer = QgsMapLayerRegistry.instance().mapLayersByName( name )[0]
    if name.startswith('Test'):
        #Specify the Order By clause. False means Descending
        for f in layer.getFeatures(QgsFeatureRequest().addOrderBy('IDfield',False)):

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.