I need code that loops between each pair of features in sequence (feature 1 with feature 2, feature 2 with feature 3...) but using only a for, I searched the forum and found similar code but with two "for" and one "if", having to go through the entire list again every time the loop happens, would there be a way for me to do this with just one for? I tried using something like "next feature" but it failed.
The original code:
iter1 = layer.getFeatures()
for feature1 in iter1:
p1 = feature1.geometry().asPoint()
# loop all points again:
iter2 = layer.getFeatures()
for feature2 in iter2:
# following line creates lines from one feature to previous feature:
if feature2.id() == feature1.id() + 1:
# create new line feature:
p2 = feature2.geometry().asPoint()
l = QgsGeometry.fromPolylineXY([p1,p2])
linha = QgsFeature()
linha.setGeometry(l)
linha.setAttributes([l.length()])
pr.addFeature(linha)
My code attempt:
features = layer.getFeatures()
for index, actualFeature in enumerate(features):
p1 = actualFeature.geometry().asPoint()
# loop all points again:
nextFeature = features.index()+1
# create new line feature:
p2 = nextFeature.geometry().asPoint()
l = QgsGeometry.fromPolylineXY([p1,p2])
linha = QgsFeature()
linha.setGeometry(l)
linha.setAttributes([l.length()])
pr.addFeature(linha)
vl.updateFields()
QgsProject.instance().addMapLayer(vl)
But one of the problems is that QgsFeatureIterator object has no attribute 'index', and I think I didn't use PyQGIS correctly. I'm still new to this language, could anyone correct the code to my idea?

previous" variable, initialized toNone, then handle initialization on the first iteration, compareactualtopreviousand put aprevious = actualat the end of the loop. Try it on something simple first, like arange(10)then step up to features. – Vince Dec 12 '23 at 03:59