Skip to content

Instantly share code, notes, and snippets.

@brendancol
Last active December 17, 2015 14:29
Show Gist options
  • Save brendancol/5625257 to your computer and use it in GitHub Desktop.
Save brendancol/5625257 to your computer and use it in GitHub Desktop.
Developer Brown Bag: Python is the shiz -- An introduction to the Python 2.7 includes: data types, conditional statements, flow control, functions, classes, arcpy basics, and scipy spatial examples
import this
# comments are made by using the pound character
# =============================================================================
# basic data types / variable assignment in Python 2.x
# =============================================================================
this_is_a_string = 'Hello and welcome to developer brown bag'
this_is_a_string = "Hello and welcome to developer brown bag..Let's cheer"
this_is_a_string = '''Hello and welcome to developer brown bag...Let's cheer "Horray"'''
this_is_a_string = """Hello and welcome to developer brown bag"""
this_is_an_int = 8
this_is_a_float = 8.0
this_is_an_int = 8 / 12 # equals 0
this_is_a_float = 8 / 12.0 # equals 0.6666666666666666
# =============================================================================
# lists - pythons default array type
# =============================================================================
this_is_a_list = [] # list
this_is_a_list = list()
this_is_a_list.append(2)
print this_is_a_list
this_is_a_list += [1]
print this_is_a_list
this_is_a_list.sort()
print this_is_a_list
# =============================================================================
# conditional statements - if; elif; else
# =============================================================================
x = None
y = None
if x and y:
print '{} :: {} are not null'.format(x, y)
elif x or y:
print '{} :: {} one of them is not null'.format(x, y)
else:
print '{} :: {} both are null'.format(x, y)
# =============================================================================
# loops - standard for loop; list comprehension; enumerate function is the shiz
# =============================================================================
items = range(0, 100, 5)
print type(items)
for i in items:
print 'standard for loop: {}'.format(i)
new_items = [i for i in items if i > 65] #list comprehension
print 'new items: {}'.format(new_items)
for index, value in enumerate(new_items):
print 'list index: {} >>> value: {}'.format(index, value)
# =============================================================================
# dictionaries - associative arrays or lookup tables or hash tables
# =============================================================================
d = {}
d['vocals'] = 'Jim Morrison'
d['keys'] = 'Ray Manzarek'
d['guitar'] = 'Robby Krieger'
d['drums'] = 'John Densmore'
print d['keys']
print d.get('bass')
print 'Instruments: {}'.format(d.keys())
print 'Ladies and Gentlemen...The Doors: {}'.format(d.values())
for instrument, name in d.items():
print '{} -> {}'.format(instrument, name)
# =============================================================================
# functions - standard functions; anonymous function using lambda expressions
# =============================================================================
def light_my_fire(temperature):
if temperature >= 451:
return 'ok...my fire is lit'
else:
return 'higher'
print light_my_fire(300)
light_my_fire = lambda temperature: temperature >= 451 and 'ok my fire is lit' or 'higher'
print light_my_fire(600)
# =============================================================================
# classes - creating new objects types; inheritance; shadowing
# =============================================================================
class MusicalGroup(object):
def __init__(self, name, genre, numPieces=5):
self.name = name
self.genre = genre
self.numPieces = numPieces
def play_music(self):
print 'Daylight come and me wanna go home'
class RockBand(MusicalGroup):
def __init__(self, name, numPieces=5):
MusicalGroup.__init__(self, name, "Rock 'n' Rock", numPieces)
def play_music(self):
print 'Welcome to the jungle...shananananananananana'
def breakup_because_of_conflicting_egos(self):
print 'I quit Axl Rose!'
g_n_r = RockBand('Guns and also Roses', numPieces=6)
g_n_r.play_music()
g_n_r.breakup_because_of_conflicting_egos()
print g_n_r.__dict__
# =============================================================================
# arcpy basic example: search cursor with where clause
# =============================================================================
import arcpy
feature_class = r'C:\gis_working_directory\school_clustering.gdb\CCD_10_11_WM'
fields = ['ncessch', 'schnam', "SHAPE@JSON", "SHAPE@XY", "SHAPE@"]
where_clause = "{} = '{}'".format('mcity', 'NEW ORLEANS')
with arcpy.da.SearchCursor(feature_class, fields, where_clause) as cursor:
for r in cursor:
for i, field in enumerate(fields):
print '{} = {}'.format(field, r[i])
print '\n'
# =============================================================================
# arcpy advanced example: integrating with third-party packages (scipy)
# =============================================================================
import scipy.spatial
bourbon_street = (-10026195.958134, 3498018.476606)
numpy_array = arcpy.da.FeatureClassToNumPyArray(feature_class, ['ncessch', 'schnam', "SHAPE@XY"], where_clause)
tree = scipy.spatial.cKDTree(numpy_array["SHAPE@XY"], leafsize=10)
radius = 1000 #meters
distances, indices = tree.query([bourbon_street], len(numpy_array), distance_upper_bound=radius)
distance_lookup = dict(zip(indices[0], distances[0]))
print distance_lookup
print [(numpy_array['schnam'][i], int(distance_lookup[i])) for i in indices[0] if i != len(numpy_array)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment