在循环期间更改变量,Python

时间:2014-12-02 19:15:24

标签: python loops variables arcpy

所以我所拥有的是我使用Python的Arcpy for ArcGIS。

我的循环外部有几个变量指向ArcMap MXD文档中的文本字段。

然后我执行一个循环,遍历缓冲层的每一行,然后我按位置选择所述缓冲区内的任何点层。

然后我想从这些点图层中获取值并填充先前声明的文本字段。

我的麻烦在于我想迭代变量,以便每次循环运行时它们指向不同的文本字段。

我的代码:

指向我的MXD文档中的文本元素

HarbName1 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName1")[0]
HarbName2 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName2")[0]
HarbName3 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName3")[0]

第一个循环

for row in rows_dfA_Asset:
   whereClause = '"HARB_CODE" = ' + str(row.getValue("Harb_Code"))
   arcpy.MakeFeatureLayer_management(dfA_Buffer, output, whereClause, "", "")
   arcpy.SelectLayerByLocation_management(dfA_Layer, "WITHIN", output, "", "NEW_SELECTION")
   test = arcpy.SearchCursor(dfA_Layer, fields="Harb_Code; NAME; CAPACACITY; HIGH_BERTH; HarbHiPerc; AvgBerth; HarbAvgPer; CLSD_DET; CLSD_NUM_M; Tot_Num_As; Num_SCH_As; PROV; GOV_SCORE; MAN_SCORE")

第二个循环这是问题

for field in test:
    count = count + 1
    print count

    HarbName(count) = str(field.getValue("NAME"))

所以归结为我需要迭代变量名称,该变量名称将与指向文本元素的全局变量匹配。

如果有人想到这样做的话,我将不胜感激。我知道我的代码不是最好的,我不是交易程序员。

2 个答案:

答案 0 :(得分:1)

我认为评论是正确的。

您要做的是重构以下内容:

HarbName1 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName1")[0]
HarbName2 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName2")[0]
HarbName3 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName3")[0]

如:

HarbName = { 1: arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName1")[0],
             2: arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName2")[0]
             3: arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName3")[0]
           }

然后最后一点将是:

for field in test:
    count = count + 1
    print count

    HarbName[count] = str(field.getValue("NAME"))

假设count是基于零的并匹配上面定义的索引

答案 1 :(得分:1)

您需要的是一份清单。然后,您可以按计数访问每个文本元素。你需要改变:

HarbName1 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName1")[0]
HarbName2 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName2")[0]
HarbName3 = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName3")[0]

要:

HarbNames = []
HarbNames.append(arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName1")[0])
HarbNames.append(arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName2")[0])
HarbNames.append(arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName3")[0])

或者,更紧凑:

HarbNames = [arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName1")[0],
             arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName2")[0],
             arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT", "HarbourName3")[0]]

然后,在第二个循环中,执行HarbNames[count](假设count从零开始):

for field in test:
    print count

    HarbNames[count] = str(field.getValue("NAME"))
    count = count + 1