2

我在下面有 python 代码,它将遍历一个表并打印出特定列中的值。未显示的是用户选择要素图层的形式。选择要素图层后,第二个下拉列表将填充该要素的所有列标题,并且用户选择他们想要关注的列。现在在 python 脚本中,我只需打印出该列中的每个值。但我想将每个值存储在 List 或 Array 中并获取 Distinct 值。我怎样才能在 Python 中做到这一点?

还有比逐行遍历表格更有效的方法吗?由于某种原因,这非常慢。

非常感谢

# Import system modules
import sys, string, os, arcgisscripting

# Create the Geoprocessor object
gp = arcgisscripting.create(9.3)
gp.AddToolbox("E:/Program Files (x86)/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")

# Declare our user input args
input_dataset = sys.argv[1] #This is the Feature Layer the User wants to Query against
Atts = sys.argv[2]          #This is the Column Name The User Selected

#Lets Loop through the rows to get values from a particular column          

fc = input_dataset

gp.AddMessage(Atts)

rows = gp.searchcursor(fc)
row = rows.next()
NewList = []

for row in gp.SearchCursor(fc):
    ##grab field values
    fcValue = fields.getvalue(Atts)
    NewList.add(fcValue)
4

2 回答 2

3

You can store distinct values in a set:

>>> a = [ 1, 2, 3, 1, 5, 3, 2, 1, 5, 4 ]
>>> b = set( a )
>>> b
{1, 2, 3, 4, 5}
>>> b.add( 5 )
>>> b
{1, 2, 3, 4, 5}
>>> b.add( 6 )
>>> b
{1, 2, 3, 4, 5, 6}

Also you can make your loop more pythonic, although I'm not sure why you loop over the row to begin with (given that you are not using it):

for row in gp.searchcursor( fc ):
    ##grab field values
    fcValue = fields.getvalue(Atts)
    gp.AddMessage(fcValue)

And btw, """ text """ is not a comment. Python only has single line comments starting with #.

于 2010-10-07T16:48:56.777 回答
1

获得不同值的一种方法是使用一个集合来查看您是否已经看到该值,并仅在它是新值时显示它:

fcValues = set()
for row in gp.searchcursor(fc):
    ##grab field values
    fcValue = fields.getvalue(Atts)
    if fcValue not in fcValues:
        gp.AddMessage(fcValue)
    fcValues.add(fcValue)
于 2010-10-07T16:53:40.763 回答