2

I'm still working on my script for vineyards. I need to count row and vine in row. So I code this :

#Nombre de rang
nbr = QgsExpression( "ID LIKE '%-1'" )
itnbr = layer.getFeatures( QgsFeatureRequest( nbr ) )
litnbr = list(itnbr)

print 'nombre de rang : ' + str(len(litnbr))

#Nombre de pied dans le rang
for i in range(len(litnbr)):
    rang = str(i+1)
    print 'rang : '+ rang
    itp = layer.getFeatures(QgsFeatureRequest().setFilterExpression("ID LIKE '{0}-%'".format(rang[i])))
    litp = list(itp)
    print 'nombre de pieds dans le rang ' + rang + ' : ' + str(len(litp))

I runned it and it works for first loop, first part of second loop and then it crash :

nombre de rang : 60
rang : 1
nombre de pieds dans le rang 1 : 6
rang : 2

exec((script), ns)
          File "<string>", line 34, in <module>
        IndexError: string index out of range

How do I fix this?

3

rang contains a single value, but you later use it as if it was an array. The line

 itp = layer.getFeatures(QgsFeatureRequest().setFilterExpression("ID LIKE '{0}-%'".format(rang[i])))

should be changed to

 itp = layer.getFeatures(QgsFeatureRequest().setFilterExpression("ID LIKE '{0}-%'".format(rang))

(if your ID = rang, else use i)

Let's note that it works in the 1st iteration as the 1st element of a single value is valid (rang[0]==rang)

0

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.