5

I have a define function ( uniqueList ) in a module which sets the unique values from a list. I'm importing the function to a new script to set the unique values from a field 'COVER', after i've set the SearchCursor and when i run it, it doesn't work.

The define function :

def uniqueList(L):
    '''Find the set of unique entries in a list.'''
    S = set(L)
    # Copy S back to L
    U = list(S)
    return U

The script :

import sys, os
pathDir = os.path.abspath('C:\Gispy\Sample_scripts\Sample_scripts\ch16\exercises\listManage')
dirName = os.path.dirname(pathDir)
relativePath = 'listManage'
modulePath = os.path.join(dirName, relativePath)
sys.path.append(modulePath)
import listManager2
import arcpy
arcpy.env.workspace = 'C:/gispy/data/ch16/park.shp'
field = arcpy.da.SearchCursor('park.shp', ['COVER'])
value = listManager2.uniqueList(field)
5
  • 1
    Your first path has wrong slashes. Either \\, / or r'\'
    – Matte
    Nov 13, 2017 at 12:48
  • 1
    Please describe what's the error ? As @Matte said one of the error in your code is the backslash syntax. What's listmanager2 ?
    – BBG_GIS
    Nov 13, 2017 at 13:12
  • it doesn't print any error, returns exit code 0.
    – DDragos
    Nov 13, 2017 at 13:18
  • but when i itterate the result it brings the attributes from the field.
    – DDragos
    Nov 13, 2017 at 13:20
  • try it then check error: os.path.abspath(r'C:\Gispy\Sample_scripts\Sample_scripts\ch16\exercises\listManage')
    – BBG_GIS
    Nov 13, 2017 at 13:20

1 Answer 1

7

Your code looks a bit complicated. Perhaps your problem is the paths. Use the r (raw) syntax for the paths and list comprehension. Also you cant set arcpy.env.workspace to a shapefile. You can set it to the folder containing the shapefile or you can set it to a geodatabase.

import arcpy,os

path = r'C:\shapefile_folder'
shapefile = r'Polygons.shp'
#If you want to set the workspace (not needed if you use full path and name of shapefile in cursor):
#arcpy.env.workspace = path
fieldname=r'COVER'

def uniqueList(L):
    '''Find the set of unique entries in a list.'''
    S = set(L)
    # Copy S back to L
    U = list(S)
    return U
#List comprehension:
all_entries = [i for i in arcpy.da.SearchCursor(os.path.join(path,shapefile),fieldname)]

Call function:

uniqueList(all_entries)

If you are only doing it once you dont need a function:

unique_values_list = list(set([i for i in arcpy.da.SearchCursor(os.path.join(path,shapefile),fieldname)]))

Or with set comprehension (curly brackets):

unique_values_list = list({i for i in arcpy.da.SearchCursor(os.path.join(path,shapefile),fieldname)}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.