I am using an update cursor to update the attributes of a shapefile using values from a list. It seems very easy, but I couldn't make it run correctly. When I run the following code, it updates all rows based on the final value in the list. Please suggest how to fix it.
cur1 = arcpy.UpdateCursor(fc)
for v in cur1:
for s in list:
val = s
v.Val = val
cur1.updateRow(v)
Answer
This looks like a simple logic error. I'm assuming that you want the first feature in the cursor to be updated with the first item in the list, then the second feature with the second item, etc. As written, you're updating the same row over and over again with each element of the list. (Then repeating the process for each row.)
Maybe your loop should look something like this instead:
listIndex = 0
cur1 = arcpy.UpdateCursor(fc)
for c in cur1:
if listIndex >= len(list):
arcpy.AddMessage("More rows than items in the list. Quitting early.")
break
val = list[listIndex]
v.Val = val
cur1.updateRow(v)
listIndex = listIndex + 1
EDIT: Corrected logic error (needed to check array length before accessing it, not after). Also fixed missing :
on if
statement.
EDIT: Following the suggestion in Paul's comment is more "Pythonic" and reduces the lines of code:
cur1 = arcpy.UpdateCursor(fc)
for tuple in enumerate(cur1):
index = tuple[0]
row = tuple[1]
if index >= len(list):
arcpy.AddMessage("More rows than items in the list. Quitting early.")
break
row.Val = list[index]
cur1.updateRow(row)
No comments:
Post a Comment