使用方法初始化变量 (Python)

Variable Initialization with Methods (Python)

为什么我的计数为零,而它应该是 29。我试图在我的函数中初始化计数,但它说它未定义。

shapefile = "Schools.shp"
work = r"c:\Scripts\Lab 6 Data"
facility = "HIGH SCHOOL"
count = 0

def numSchools(work, shapefile, facility):

    whereClause = "\"FACILITY\" = 'HIGH SCHOOL' " # where clause for high schools
    cursor = arcpy.SearchCursor("Schools.shp", facility)
    result = arcpy.GetCount_management(cursor)
    for result in cursor:
        count = int(result.getOutput(0))# Get the first value from the Result object
    return count

print ("The number of " + facility + " are:"), int(count) 

在最基本的形式中,此代码 returns 学校的正确数量。

import arcpy

arcpy.env.workspace = r"c:\Scripts\Lab 6 Data"
result = arcpy.GetCount_management("Schools.shp")
count = int(result.getOutput(0)) 
print ("The number of rows in 'schools' is "),int(count)

但是,Schools.shp 是一个包含 201 所学校的文件。

我需要在该文件中找到一个名为 'facilities' 的字段,然后在其中获取 'high schools' 的编号(我知道如何执行这部分)。但是我还需要这段代码作为一个函数工作(这是我遇到的问题)。

虽然你的问题没有解决,但我想你正在寻找这个!

print ("The number of " + facility + " are:", int(count) ) 
            searchCurs = arcpy.da.SearchCursor(shapefile, field, whereClause)
            row = searchCurs.next()
            for row in searchCurs:
                            value = row[0]
                            high_schools = [row[0] for row in arcpy.da.SearchCursor(shapefile, field, whereClause)]
                            count = len(high_schools)
                            print count