Feed on
Posts
Comments

Archive for the 'Python' Category

to custom sort a list on the fly, try using the lambda function to do a quick definition of the cmp function.  for instance, to sort the list ‘ids’, using each ‘id’ value in an ancillary dictionary ‘id_dict’: ids.sort(cmp=lambda a,b:id_dict[b] – id_dict[a])

let’s say you’ve got a list of the numbers 0 through 4 and you wanted all 32 possible combinations of them.  to get that list: list_of_five = range(0,5)    swap_list_list = [[]] for swap in list_of_five:     temp_lists = []     for list_stub in swap_list_list:         this_list = copy.copy(list_stub)         this_list.append(swap)      […]

sort a python dictionary

let’s say you’ve got a dictionary keyed by strings and whose values are numbers.  if you’d like to sort those keys by those values, here’s a quick way to do so: sorted_keys = sorted(my_dict.keys(), key=lambda x:my_dict[x]) [thanks Paul!]

when you execute a program in python, the program’s name can be found with the following command:  import sys  print sys.argv[0]  to get the full path to the program, use the abspath command:  import os  os.path.abspath(sys.argv[0])  

to make a file executable from python, use the following template:  >> import os>> my_filename = “file.txt”>> os.chmod(my_filename,0755)

flush python’s print buffer

to flush the print buffer in python:  >> sys.stdout.flush() 

real simple:  >> abs(val) 

to not have the output of subprocess.check_call print out in python, pass the output to /dev/null like so: subprocess.check_call(angst_call,stdout=open(os.devnull,”w”))

this is almost certainly not the best way to read the output of a python system call.  but, it works.    let’s say i’d like to read the results of a call to ls.  here’s how to do it: import subprocess proc = subprocess .Popen([ls],stdout=sub.PIPE) print proc.stdout.read()

let’s say you want to make an array of all the numbers between 5 and 7, separated by the interval 0.33 in python. one way to do that would be: min = 5.0 max = 7.0 interval = 0.33 my_list = [min + val*interval for val in range(int((max-min)/interval))]

« Prev - Next »