如何解决游标由于IndexError而无法更新字段
我正在使用arcpy.da.UpdateCursor
用列表中的元素更新UnitName
字段。我的脚本主要基于this question。
这成功执行:
import arcpy
#fields from the feature class table
field = ['Unit','UnitName']
#use a cursor to parse the table of the feature class
with arcpy.da.UpdateCursor(fc,field) as cursor:
for row in cursor:
unit = row[0] #get Unit in field list
s = str(unit).split() #split strings in Unit field
print(s) #print list
以下是打印输出的一些示例:
['200']
['STE','112']
['STE','L']
['UNIT','A']
['STE','B']
['STE','A']
['None']
['None']
但是,当我在打印语句上添加索引号时,会得到IndexError: list index out of range
。有趣的是我没有立即得到错误。在错误发生之前,将打印一堆元素。我认为是因为None
元素。
import arcpy
#fields from the feature class table
field = ['Unit',field) as cursor:
for row in cursor:
unit = row[1] #get Unit in field list
s = str(unit).split() #split strings in Unit field
print(s[1]) #print element in second position
row[1] = s[1] #create variable for the element
cursor.updateRow(row) #use cursor to update "UnitName" field with element in second position
200
112
L
A
B
A
Traceback (most recent call last):
File "\GIsstaff\Jared\Python Scripts\ArcGISPro\usps_ADDRE_copy.py",line 40,in <module>
unitname()
File "\GIsstaff\Jared\Python Scripts\ArcGISPro\usps_ADDRE_copy.py",line 34,in unitname
print(s[1])
IndexError: list index out of range
解决方法
我通过访问列表中的最后一项而不是第二项来解决了我的问题。
此:
print(s[-1]) #prints None elements too
不是这样的:
print(s[1])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。