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
答案 0 :(得分: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]
答案 1 :(得分:1)
答案:感谢@ nils-werner和@goyo指出我正确的方向:我需要在Move iterTwo = layerTwo.getFeatures()
之前通过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