ABSTRACT

Learning goal: You can sort your data according to a custom param-eter or column. 8.1 IN THIS CHAPTER YOU WILL LEARN

• How to sort iterable objects (lists, tuples, dictionaries)

• How to sort tables

• How to sort in ascending and descending order

• How to sort tables by a given column

• How to sort the output of BLAST according to a given parameter

8.2.1 Problem Description

A common need in dealing with tables consists of sorting them. is task can be accomplished using MS Excel or similar Oce programs. However, this becomes complicated if you have to manage big amounts of data. Moreover, you may want to sort the table based on given conditions or to automatize the sorting procedure. Sorting data can be easily done using a Python script. e following Python session sorts an input table by the values of its second column in descending order. To do this, the built-in function sorted() is used in combination with the itemgetter function, which is imported from the operator module. A list comprehension (see Chapter 4, Section 4.3.3) is used to convert the

string elements of a list into oating numbers (at the beginning) and vice versa (at the end). e program works as follows: the input le containing a table of numbers is read to a Python table (a nested list of oats). en the table is sorted, and the elements are converted back to strings. e elements belonging to the table columns are joined by a tabulator ('\t') and nally printed to the screen.