使用Python向数组添加值并获得不同的值

2 投票
2 回答
6944 浏览
提问于 2025-04-16 05:09

我有一段Python代码,它会遍历一个表格,并打印出特定列中的值。这里没有显示的是用户选择一个特征层的方式。一旦选择了特征层,第二个下拉框就会填充该特征的所有列标题,用户可以选择他们想要关注的列。然后在Python脚本中,我只是简单地打印出该列中的每个值。但我想把每个值存储在一个列表或数组中,并获取不同的值。我该如何在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 个回答

1

获取不同值的一种方法是使用一个集合(set),来检查你是否已经见过这个值。只有当这个值是新的时候,才显示出来:

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

另外,你可以让你的循环更符合Python的风格,虽然我不太明白你为什么要循环遍历这一行(因为你并没有使用它):

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

顺便说一下,""" text """ 其实 不是 注释。Python 只有以 # 开头的单行注释。

撰写回答