2
votes

I've got a loop that is supposed to select features and keep looping until it is no longer selecting new features

arcpy.SelectLayerByLocation_management("antiRivStart","INTERSECT","polygon")

previousselectcount = -1
selectcount = arcpy.GetCount_management("StreamT_StreamO1")
while True:
#selectCount = arcpy.GetCount_management("StreamT_StreamO1")
    mylist = []
    with arcpy.da.SearchCursor("antiRivStart","ORIG_FID") as mycursor:
        for feat in mycursor:
            mylist.append(feat[0])
            liststring = str(mylist)
            queryIn1 = liststring.replace('[','(')
            queryIn2 = queryIn1.replace(']',')')
    arcpy.SelectLayerByAttribute_management('StreamT_StreamO1',"ADD_TO_SELECTION",'OBJECTID IN '+ queryIn2 )
    arcpy.SelectLayerByLocation_management("antiRivStart","INTERSECT","StreamT_StreamO1","","ADD_TO_SELECTION")
    previousselectcount = selectcount
    selectcount = arcpy.GetCount_management("StreamT_StreamO1")
    print str(selectcount), str(previousselectcount)
    if selectcount == previousselectcount:
        break

By my reckoning, once it starts print the name number twice it should stop, but it doesn't, its keeps print "15548 15548" over and over again. Is it ingnoring the break or is the if condition not being met?

I've also tried with

while selectcount != previousselectcount:

but this gave me the same result

1
I know nothing about Gis, so I'm asking are really selectcount of type int? And if not, what does it prints when you use repr instead of str? - Lærne
"Is it ingnoring the break" - obviously not. "is the if condition not being met" - well, that has to be the case. Check the type of those variables. - Karoly Horvath
Here, look at that : gis.stackexchange.com/questions/55246/… . Your problem is that the selectcount always receive a new different object, even though the underlying number is the same. Thus they're never equal. - Lærne

1 Answers

1
votes

Variables in Python are dynamic. Just because you initialise previousselectcount as an integer doesn't mean it will be one when you call previousselectcount = selectcount. You can feel free to get rid of that line.

If you replace:

selectcount = arcpy.GetCount_management("StreamT_StreamO1")

With:

selectcount = int(arcpy.GetCount_management("StreamT_StreamO1").getOutput(0))

For both lines you'll be comparing the integer values instead of whatever the equality operator is comparing for the object.

Even better, why not write a function to do it for you:

def GetCount():
    return int(arcpy.GetCount_management("StreamT_StreamO1").getOutput(0))

Save yourself repeating yourself.