将值添加到数组并使用Python获取不同的值

时间:2010-10-07 16:41:38

标签: python arcgis

我在下面有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)

2 个答案:

答案 0 :(得分:3)

您可以在一组中存储不同的值:

>>> 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}

此外,你可以让你的循环更加pythonic,虽然我不知道为什么你循环开始行(假设你没有使用它):

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

顺便说一句,""" text """ 不是评论。 Python只有以#开头的单行注释。

答案 1 :(得分: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)