1. Assign values from a list that is shorter or longer than the original list
I find this simple function handy since this allows me to assign values from a list that is shorter or longer than the target list. It acts like partial assignment, leaving elements intact in my original list if source list is shorter.
def assignValues(list1, list2): mapFunc = lambda a,b: a if b is None else b origLen = len(list1) list1[:] = map(mapFunc, list1, list2)[:origLen] tgtList = [1,2,3,4] srcList = [0,0] assignValues(tgtList, srcList)
2. Overriding [] (indexing) in python for 2d indexing We know that we can use __getitem__ to assign an array like behavior (or make object iterable). But how about making object behave like 2 or 3 dimensional array? You can actually pass tuple as a key to __getitem__ and then use unpacking feature of python. I found the following code online on activestate recipe website.
def __getitem__(self, (row, column)): return self._data[row][column]
3. Some great recipes on python website Some great code recipes and a very useful module. http://docs.python.org/library/itertools.html#recipes
No comments:
Post a Comment