为什么我的python循环停止时不会?

时间:2015-10-20 12:56:08

标签: python loops while-loop arcgis break

我有一个循环,应该选择功能并保持循环,直到它不再选择新功能

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

根据我的估算,一旦它开始打印名称编号两次它应该停止,但它没有,它保持打印" 15548 15548"一遍又一遍地。它是在徘徊休息还是未满足的条件?

我也试过

while selectcount != previousselectcount:

但这给了我相同的结果

1 个答案:

答案 0 :(得分:1)

Python中的变量是动态的。仅仅因为您将previousselectcount初始化为整数并不意味着当您调用previousselectcount = selectcount时它将是一个整数。你可以随意摆脱那条线。

如果替换:

selectcount = arcpy.GetCount_management("StreamT_StreamO1")

使用:

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

对于这两行,您将比较整数值,而不是等于运算符对象的比较。

更好的是,为什么不写一个函数为你做这个:

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

让自己重复自己。