gpt4 book ai didi

python - 使用 arcpy : strange behaviour of SearchCursor 在列表中加载要素类

转载 作者:太空狗 更新时间:2023-10-30 02:48:42 26 4
gpt4 key购买 nike

使用 arcpy,我的目的是将要素类存储在列表中以供进一步处理。每行都是 {'field name': value} 的字典,包括几何图形。

完成此任务的最 pythonic 方法应该是使用列表理解:

fc = '/path/to/fc'
fields = [f.name for f in arcpy.ListFields(fc)] # get field list
features = [[row.getValue(f) for f in fields] for row in arcpy.SearchCursor(fc)]

此方法适用于数据,但列表中的几何图形都是相同的(在 fc 中检索到的最后一个几何图形)。 This behaviour of SearchCursor has already been commented on StackOverflow .

我尝试了另一种方法:

fc = '/path/to/fc'
shape_field = arcpy.Describe(fc).shapeFieldName

# load geometry in a list
geom = arcpy.Geometry()
feat = [{shape_field: f} for f in arcpy.CopyFeatures_management(fc, geom)] # slow

# load data in a list
fields = [f.name for f in arcpy.ListFields(fc)]
data = [dict([(f, row.getValue(f)) for f in fields if f != shape_field]) for row in arcpy.SearchCursor(fc)] # slow

# merge
merge = zip(feat, data)
merge = [dict([(k, v) for adict in line for (k, v) in adict.items()]) for line in merge] # sorry for that...

它适用于我的数据集,但是:

  • 它很慢。
  • 我不确定断言数据和专长的顺序相同是否安全。

对此有何看法?

最佳答案

如果可能,请迁移到使用 10.1,您将获得 arcpy.da,这是一个性能显着提高的游标 API。 I've written a log post on this very topic of getting dictionaries back .几何体将全部相同,因为它在内部使用回收游标,因此在 10.0 中,您需要获取 shape.__geo_interface__ 并使用 AsShape 将其恢复为几何对象。

返回行的顺序是相当随意的:您可以期望它在 shapefile 中每次都是相同的没有 where 子句,仅此而已,所以您的两次通过方法获胜真的很可靠。

考虑到所有这些,您可以这样做:

def cursor_to_dicts(cursor, field_names):
for row in cursor:
row_dict = {}
for field in field_names:
val = row.getValue(field)
row_dict[field] = getattr(val, '__geo_interface__', val)
yield row_dict

fc = '/path/to/fc'
fields = [f.name for f in arcpy.ListFields(fc)] # get field list
features = list(cursor_to_dicts(arcpy.SearchCursor(fc), fields))

神奇的是 getattr() 调用——尝试获取 value.__geo_interface__(如果存在),否则默认为 value

由于这个问题不是关于一般的 Python 语言,而是关于特定于 GIS 的 API (arcpy),所以您以后最好在 gis.stackexchange 上提出这样的问题。

关于python - 使用 arcpy : strange behaviour of SearchCursor 在列表中加载要素类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11869473/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com