2017-07-18 24 views
0

答:感謝@尼爾斯-Werner和@goyo指着我在正確的方向:我需要通過Move iterTwo = layerTwo.getFeatures() right before for feat in iterTwo :這樣:如何迭代兩個不同的qgis圖層的特徵?

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 
+3

也許'layerTwo.getFeatures()'返回將一次運行後排出的迭代符。你有沒有嘗試過使用'list(layerTwo.getFeatures())'將它轉換成列表?或者,您可以嘗試'在layerTwo.getFeatures()'中使用壯舉。 –

+0

是這樣做的,因爲每次迭代iterOne只需要'print layerOneId'一次 –

+1

第二次迭代器在外循環的第一次迭代中耗盡,您將需要在每次迭代中重新創建它。將iterTwo = layerTwo.getFeatures()放在'之前移動iterTwo:' – Goyo

回答

0

ANSWER訪問與ID的元組:感謝@尼爾斯-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 
1

我會用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]

相關問題