如何迭代两个不同 qgis 层的特征?

How to iterate over features of two different qgis layers?

答案:感谢@nils-werner 和@goyo 为我指明了正确的方向:我需要通过 Move iterTwo = layerTwo.getFeatures() right before for feat in iterTwo : 原样:

layerOne = QgsVectorLayer( '~/FirstLayer.shp', 'layerOne', 'ogr')
layerTwo = QgsVectorLayer( '~/SecondLayer.shp', 'layerTwo', 'ogr')

iterOne = layerOne.getFeatures()

for feature in iterOne: 
    layerOneId = feature.attributes()[0]
    print layerOneId
    iterTwo = layerTwo.getFeatures()
    for feat in iterTwo :
        layerTwoId = feat.attributes()[0]
        print "LayerOneId",LayerOneId, "LayerTwoId", LayerTwoId"
        # do something if LayerOneId == LayerTwoId

我有两层,我想比较一下:

layerOne = QgsVectorLayer( '~/FirstLayer.shp', 'layerOne', 'ogr')
layerTwo = QgsVectorLayer( '~/SecondLayer.shp', 'layerTwo', 'ogr')

iterOne = layerOne.getFeatures()
iterTwo = layerTwo.getFeatures()
for feature in iterOne: 
    layerOneId = feature.attributes()[0]
    print layerOneId
    for feat in iterTwo :
        layerTwoId = feat.attributes()[0]
        print "LayerOneId",LayerOneId, "LayerTwoId", LayerTwoId"
        # do something if LayerOneId == LayerTwoId

此代码在 LayerOne 的第一次迭代中正确运行,但随后仅在第一层上迭代而不检查第二层。结果如下所示:

LayerOneId, 0

LayerOneId, 0, LayerTwoId, 0

LayerOneId, 0, LayerTwoId, 1

...

LayerOneId, 0, LayerTwoId, n

LayerOneId, 1

LayerOneId, 2

...

LayerOneId, n

为什么我的函数只迭代第一层的第一个特征?

更准确地说,我正在寻找在 python 控制台中有效的结果:

arrayOne = [1,2]
arrayTwo = [1,2]
for a in arrayOne :
    for b in arrayTwo:
        print a,b
>>> 1,1
>>> 1,2
>>> 2,1
>>> 2,2

我会使用 itertools.product 来迭代这两个特征

import itertools

layerOne = QgsVectorLayer( '~/FirstLayer.shp', 'layerOne', 'ogr')
layerTwo = QgsVectorLayer( '~/SecondLayer.shp', 'layerTwo', 'ogr')

for features in itertools.product(layerOne.getFeatures(), layerTwo.getFeatures()):

    id = tuple(feat.attributes()[0] for feat in features)

    print "LayerOneId" ,id[0] , "LayerTwoId", id[1]

    if id[0] == id[1]:
        pass
        # code if both id's match

features是一个具有两层特征的元组。如果您需要除 id 之外的更多功能,您可以将它们转置为 zipped_attributes = zip(*feat.attributes() for feat in features) 之类的东西,并使用 id = zipped_attributes[0]

访问带有 ids 的元组

答案:感谢@nils-werner 和@goyo 为我指明了正确的方向:我需要在 feat in iterTwo : 之前通过 Move iterTwo = layerTwo.getFeatures() 就这样:

layerOne = QgsVectorLayer( '~/FirstLayer.shp', 'layerOne', 'ogr')
layerTwo = QgsVectorLayer( '~/SecondLayer.shp', 'layerTwo', 'ogr')

iterOne = layerOne.getFeatures()

for feature in iterOne: 
    layerOneId = feature.attributes()[0]
    print layerOneId
    iterTwo = layerTwo.getFeatures()
    for feat in iterTwo :
        layerTwoId = feat.attributes()[0]
        print "LayerOneId",LayerOneId, "LayerTwoId", LayerTwoId"
        # do something if LayerOneId == LayerTwoId