python Built-In Types for sets

689
5
10-30-2013 08:33 AM
LarryAdgate
Occasional Contributor
Below is an example given, in the python literature, for a python built-in type: The instructions say: Returns a new set with elements in the set that are not in the others. Is there someone that can provide an example of how this built-in is used? A world of thanks. Larry Adgate-see attachment  

set - other - ....
Tags (2)
0 Kudos
5 Replies
JasonScheirer
Occasional Contributor III
An example:

a, b = {1, 2, 3, 4}, {3, 4, 7, 10}
c = a - b
print c


will print

set([1, 2])


Or say we have two tables (table_one and table_two) with a field named "name". You want all the names in table_one that aren't in table_two.

set_one = set(r[0] for r in arcpy.da.SearchCursor("table_one", "name"))
set_two = set(r[0] for r in arcpy.da.SearchCursor("table_one", "name"))
print "Items unique to table_one: {}".format(", ".join(sorted(set_one - set_two)))
0 Kudos
LarryAdgate
Occasional Contributor
Jason, the code for table_one and table_two works well for text only. Can it be modified if the fields in the shapefiles were double or a float?, Thanks Larry
0 Kudos
StacyRendall1
Occasional Contributor III
You can use sets to find the unique values of a bunch of values...
0 Kudos
JasonScheirer
Occasional Contributor III
It works for most basic types, so the same code would work on doubles/floats/ints/whatever as well.
0 Kudos
ChrisSnyder
Regular Contributor III
I like sets a lot. Most people just use them for calculating unique values, but the real power is in using the set()'s union, intersect, difference, etc. functions... Extreemly fast and efficient!

One practical example I use this for is I have this large polygon layer I need to convert to raster in order to get elevation and slope values (from a DEM) using zonal statsistics. A number of the polygons (20% or so) are too small to be converted to a raster, and for those, I still need to get spot elevation and slope values for the centroids via the Sample tool.

Basically I make a set for the OIDs for all my original polygons, and another set for the VALUEs of the raster version (which are the OIDs that "made it" to the raster). Now I need to figure out what polygons I must convert to centroids (so as to run the sample tool). BTW: Dealing with  2.5 million polgons.

For example:

>>> set1 = set((1,2,3,4,5,6,7,8,9,10)) #all the OIDs in the polygon layer
>>> set2 = set((1,2,3,7,8,9)) #the OIDs that made it to the raster layer
>>> print set1.difference(set2)
set([10, 4, 5, 6]) #The polygon OIDs that I need to derive centroids for and then use the Sample tool on
0 Kudos