[Tutor] how to sort the data inside the file.
Kent Johnson
kent37 at tds.net
Mon Dec 31 18:18:14 CET 2007
Chris Fuller wrote:
> This is a classic case for the use of regular expressions. A powerful tool,
> but can be tricky. I create a RE for a record, and than use the findall()
> function to get all of them in a list. I'll walk you through it.
> # seperate into records
> lin = re.findall('\s*([^\s]+)\s+([^\s]+)\s+(\d+)( [kM])?bytes', s)
This is just splitting on whitespace, you could just use s.split().
> # now sort
> lout.sort(lambda a,b: cmp(a[2], b[2]))
> The other tricky bit is the sort. In python, lists can be sorted in place, if
> you pass a function that determines the relative precedence of two elements.
Recent versions of Python have a better (faster, easier to understand)
way to do this using the key parameter to sort. The above could be
written as
lout.sort(key=lambda a: a[2])
or, better:
import operator
lout.sort(key=operator.itemgetter(2))
Kent
More information about the Tutor
mailing list