User:Alvations/py cheatsheet
Appearance
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.
String Manipulation
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)
List/Sets Manipulation
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]
Dictionary/Collections Manipulation
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]