如何使用 None 数据类型对 updatecursor 中的项目求和
How to sum items in updatecursor with None data types
使用 ESRI 的 arcpy 在 python 中工作,我尝试使用 arcpy updateCursor 对多个字段的值求和。我正在尝试将 None 项转换为 0。但是,我想不出一种方法来转换 None 项。我对任何事情都持开放态度。
with arcpy.da.UpdateCursor(feature_class, score_fields) as cursor:
for row in cursor:
[0 if x==None else x+4 for x in row]
print row
row[len(score_fields)-1] = sum(row[i] for i in range(len(score_fields)))
cursor.updateRow(row)
Returns:
[-4, -4, None, None, -4, None, -4, -4]
错误:
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
谢谢!
您可以使用 if 语句过滤列表中的 None
值:
sum(row[i] for i in range(len(score_fields)) if row[i] is not None)
您应该通过将列表理解的结果分配给 row
来更新 row
:
for row in cursor:
row = [0 if x is None else x+4 for x in row]
此外,请注意,由于只有一个 None
对象,因此使用 is
进行测试比使用 ==
更好;更 Pythonic,更高效。
使用 ESRI 的 arcpy 在 python 中工作,我尝试使用 arcpy updateCursor 对多个字段的值求和。我正在尝试将 None 项转换为 0。但是,我想不出一种方法来转换 None 项。我对任何事情都持开放态度。
with arcpy.da.UpdateCursor(feature_class, score_fields) as cursor:
for row in cursor:
[0 if x==None else x+4 for x in row]
print row
row[len(score_fields)-1] = sum(row[i] for i in range(len(score_fields)))
cursor.updateRow(row)
Returns:
[-4, -4, None, None, -4, None, -4, -4]
错误:
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
谢谢!
您可以使用 if 语句过滤列表中的 None
值:
sum(row[i] for i in range(len(score_fields)) if row[i] is not None)
您应该通过将列表理解的结果分配给 row
来更新 row
:
for row in cursor:
row = [0 if x is None else x+4 for x in row]
此外,请注意,由于只有一个 None
对象,因此使用 is
进行测试比使用 ==
更好;更 Pythonic,更高效。