如何汇总updatecursor中的项目与无数据类型
问题描述:
使用ESRI的arcpy python工作,我试图通过arcpy updateCursor跨多个字段求和值。我试图将无项目转换为0.但是,我无法找出一种方法来转换None项目。我对任何事情都很开放。如何汇总updatecursor中的项目与无数据类型
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)
返回:
[-4, -4, None, None, -4, None, -4, -4]
错误:
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
谢谢!
答
您应该更新row
:也
for row in cursor:
row = [0 if x is None else x+4 for x in row]
,请注意,由于只有一个None
对象,所以最好使用is
进行测试,而不是使用==
;更多Pythonic,更高性能。
答
您可以使用if语句到列表过滤None
值:通过指定列表理解的结果row
sum(row[i] for i in range(len(score_fields)) if row[i] is not None)
+1
这也工作了,谢谢。摩西的答案更适合我的其他未列出的代码。 – Dodgens
看看这个[在python中处理NoneTypes](https://stackoverflow.com/questions/9316697/handle-variable-that-could-be-none) – WhatsThePoint