Monday 23 November 2015

ArcPy nested loop problem


I have a question connected with ArcPy. I was trying to make a nested loop with 2 cursors - 1st with 2 elements and 2nd with 5 elements. The statement should return 10 connections, e.g. 1-1, 1-2, ... 2-5. Here is part of my code:


import arcpy
import os.path

folder = "Z:\WOLGA"
na="na"
baza = "testy.mdb"
dataset = "network_analyst"

arcpy.env.workspace = os.path.join(folder, na, baza, dataset)
shapePocz = os.path.join(folder, na, baza, dataset, "dom")

listaPktPocz = arcpy.SearchCursor(shapePocz, "", "", "", "")
shapeKonc = os.path.join(folder, na, baza, dataset, "punkty_docelowe")
listaPktKonc = arcpy.SearchCursor(shapeKonc, "", "", "", "")
shapeKoncName = arcpy.Describe(shapeKonc).shapeFieldName
shapePoczName = arcpy.Describe(shapePocz).shapeFieldName

for pktPocz in listaPktPocz:

for pktKonc in listaPktKonc:
print str(pktPocz.numer) + " - " + str(pktKonc.numer)

For now I got such connections as: 1-1, 1-2, 1-3, 1-4, 1-5 only. The outer loop is not being executed properly.



Answer



The problem is definitely the old-type cursor. It often makes some problems with nested loops. I recommend you to use da.SearchCursor. The code should look like this:


with arcpy.da.SearchCursor(shapePocz, ["numer"]) as searchCursOuter:
for pktPocz in searchCursOuter:
with arcpy.da.SearchCursor(shapeKonc, ["numer"]) as searchCursInner:
for pktKonc in searchCursInner:

print str(pktPocz[0]) + " - " + str(pktKonc[0])

I bet it works.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...