Jump to content

User:Alvations/py cheatsheet

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Alvations (talk | contribs) at 02:19, 27 November 2012 (Created page with 'I am sort of new to python programming though not new to programming so here I've compiled some recipes that I often used in my...'). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

I am sort of new to python programming though not new to programming so here I've compiled some recipes that I often used in my NLP pursuit.

Insert a substring into a string

Often I want to insert a character or substring at a specified position. I've no idea why python strings doesn't have an in-built insert though.

# To insert a string into an original string at a specified position.
def insert(original, insertee, pos):
  return original[:pos:] + insertee + original[pos:]
print insert ("hoses", "r", 2)

Find the difference between 2 lists

Without further ado, ...

# Returns the difference between 2 lists.
def getDiff(lista, listb):
  return [x for x in lista if x not in listb]

Find the overlap between 2 lists

I'm kind of a Lesk algorithm junkie so I always want to find overlaps between 2 lists/maps/set/dicts/etc.

# Returns the overlap between 2 lists.
def getOverlap(lista, listb):
  return [x for x in lista if x in listb]

Find the first instance of a key given a value in a dictionary

# Gets first instance of matching key given a value and a dictionary.    
def getKey(dic, value):
  return [k for k,v in sorted(dic.items()) if v == value]