BMI Students

Friday, April 15, 2005

Useful Python functions

Recently, I have been using these functions a lot. Maybe they will be of use to others.
These functions:

  • sort a list of objects by an attribute, eg sort_by_attr(people, 'name')
  • sort a list of objects by a list of attributes eg sort_by_attrs(people, ['lastname','firstname']
  • print out all of the attributes of an object.

Read more

In the bleak bleak perl days, I might have made a list of blast hits as a dictionary of dictionaries, eg hit[gene1][gene2] = 10. Of course it's much neater to do it like this
hit = Container()
hit.gene1 = gene1
hit.gene2 = gene2
hit.score = score
Then you can sort by score, gene1, gene2 etc etc..

def sort_by_attr(seq,attr):
"""stably sort by an attribute"""
seq2 = [[getattr(s,attr),i,s] for i,s in enumerate(seq)]
return [s[2] for s in seq2]

def sort_by_attr_inplace(seq,attr):
"""stably sort by an attribute in place"""
seq[:] = sort_by_attr(seq,attr)

def sort_by_attrs(seq,attrs):
"""sort by a few attributes"""
import copy
seq2 = copy.copy(seq)
for attr in attrs:
seq2 = sort_by_attr(seq2,attr)

return seq2

def sort_by_attrs_inplace(seq,attrs):
"""sort by a few attributes in place"""
for attr in attrs:
seq[:] = sort_by_attr(seq,attr)

def print_all_attrs(obj_instance):
attrs = dir(obj_instance)
for attr in attrs:
if attr[:2] == '__':
print attr, getattr(obj_instance,attr)


Post a Comment

<< Home