Posted in Python on October 3rd, 2006 1 Comment »
inverting a dictionary in python – that is, index it’s keys using it’s values – requires only one line of code: dict(map(lambda item:(item[1],item[0]),my_dict.items())) for instance, the dictionary a: >>> a = dict() >>> a['me'] = 5 >>> a['you'] = 5 >>> a['her'] = 6 >>> a['him'] = 245 >>> print a {‘me’: 5, ‘you’: 5, […]
Posted in Python on September 21st, 2006 No Comments »
the trouble with dicts or hashes is that there’s no easy way to search for a value and return a key. for instance, i’m not aware of a simple python command to find the dict key associated with the smallest value in the dict. nevertheless, there are quick and dirty ways to pull off the […]
Posted in Python on August 4th, 2006 31 Comments »
to iterate over a list in reverse order in python, i use the ‘reverse’ method. i’m sure there are faster ways to do this in terms of running time, but its hard to conceive of anything easier to implement. here goes: to iterate over ‘my_list’ backwards, write: my_list.reverse() for item in my_list: print item
Posted in Python on July 18th, 2006 14 Comments »
assuming you’re running some *nix (including mac os x), here’s how to create a directory from within a python script. note that we need to check if the directory exists before creating a directory (if you try and overwrite a directory, python will throw an error). here goes: import os; … dirname = “my_dir_name” if […]
Posted in Python on July 18th, 2006 No Comments »
to get the time in python: import time; … time.localtime()
Posted in Python on May 25th, 2006 2 Comments »
say we have the python list: >>x = [5,6,5] to remove the duplications, use the following code snippet: >>x_nodups = dict(map(lambda i: (i,1),x)).keys() ::thanks to walter underwood::
Posted in Python on April 17th, 2006 10 Comments »
assuming you’ve got some string named foo, to remove leading white space: >>> foo.lstrip() to remove trailing whitespace: >>> foo.rstrip() to remove both lead and trailing whitespace: >>> foo.strip()
Posted in Python on April 17th, 2006 4 Comments »
to create a double dictionary in python, the following won’t work: >>> x = dict() >>> x[1][1] = “foo” instead, you need only one set of brackets: >>> x = dict() >>> x = [1,1] = “foo”
Posted in Python on April 17th, 2006 No Comments »
to sample from the uniform distribution between 0 and 1, you need to import the random module. then, simply call the random method: >>> import random; >>> rand_num = random.random()
Posted in Python on April 17th, 2006 No Comments »
python’s so damn intuitive. to sort a list: >>> list_name.sort()