如何限制游标中的循环迭代?

时间:2014-06-24 22:49:28

标签: python cursor arcpy

我在SearchCursor中使用for循环来迭代功能类中的功能。

import arcpy

fc = r'C:\path\to\featureclass'

with arcpy.da.SearchCursor(fc, ["fieldA", "FieldB", "FieldC"]) as cursor:
    for row in cursor:
        # Do something...

我目前正在对脚本进行故障排除,并且需要找到一种方法来将迭代限制为,例如,当前配置的是5而不是3500。我知道限制for循环中迭代次数的最基本方法如下:

numbers = [1,2,3,4,5]

for i in numbers[0:2]
     print i

但是,在迭代游标对象时,此方法不起作用。我可以使用什么方法来限制for语句中包含的游标对象中with循环的迭代次数?

3 个答案:

答案 0 :(得分:1)

您可以使用列表推导来获取所有内容,然后只使用您需要的前五行。请查看以下示例:

max = 5 #insert max number of iterations here
with arcpy.da.SearchCursor(fc, ["fieldA", "FieldB", "FieldC"]) as cursor:
    output = [list(row) for row in cursor][:max]

重要的是要注意每一行都是一个元组输出,因此list()方法用于创建一个可用于任何需要的二维列表。即使您的数据集是3500行,这也应该在很短的时间内完成。我希望这有帮助!

答案 1 :(得分:1)

添加计数器和逻辑语句以限制迭代次数。例如:

import arcpy

fc = r'C:\path\to\featureclass'

count = 1 # Start a counter

with arcpy.da.SearchCursor(fc, ["fieldA", "FieldB", "FieldC"]) as cursor:
    for row in cursor:
        # Do something...
        if count >= 2:
            print "Processing stopped because iterations >= 2"
            sys.exit()

        count += 1

答案 2 :(得分:0)

一种可能的方式:

for index, row in enumerate(cursor):
  if index > x:
    # do something...
  else:
    # do something...