简体   繁体   English

为什么我的 python while 循环停止?

[英]Why wont my python while loop stop?

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.据我估计,一旦它开始打印名称编号两次,它应该停止,但它没有,它会一遍又一遍地打印“15548 15548”。 Is it ingnoring the break or is the if condition not being met?是忽略了中断还是没有满足 if 条件?

I've also tried with我也试过

while selectcount != previousselectcount:

but this gave me the same result但这给了我同样的结果

Variables in Python are dynamic. Python 中的变量是动态的。 Just because you initialise previousselectcount as an integer doesn't mean it will be one when you call previousselectcount = selectcount .仅仅因为您将previousselectcount初始化为一个整数并不意味着当您调用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.避免重复自己。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM