- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
使用 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/
我正在开发一个需要能够平均三个数字的 Facebook 应用程序。但是,它总是返回 0 作为答案。这是我的代码: $y = 100; $n = 250; $m = 300; $number = ($y
我只是无法弄清楚这一点,也找不到任何对我来说有意义的类似问题。我的问题:我从数据库中提取记录,并在我的网页上以每个面板 12 条的倍数显示它们。因此,我需要知道有多少个面板可以使用 JavaScrip
我是一名优秀的程序员,十分优秀!