Feed on
Posts
Comments

Archive for the 'Python' Category

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, […]

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 […]

read a list backwards in python

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

create a directory in python

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 […]

get the time in python

to get the time in python: import time; … time.localtime()

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::

remove whitespace in python

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()

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”

get a random number in python

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()

sort a list in python

python’s so damn intuitive. to sort a list: >>> list_name.sort()

« Prev - Next »