UNIX-style sort in Python?
adalke at mindspring.com
Mon Oct 18 02:42:46 CEST 2004
Kotlin Sam wrote:
> % sort -t, +2 +5 imputfilename <return>
> So, is there a module or function already available that does this?
In newer Pythons (CVS and beta-1 for 2.4) you can do
fields = line.split("\t")
return fields, fields
sorted_lines = sorted(open("imputfilename"), key=get_fields)
For older Pythons you'll need to do the "decorate-sort-undecorate"
("DSU") yourself, like this
lines = [get_fields(line), line for line in open("imputfilename")]
sorted_lines = [x for x in lines]
There is a slight difference between these two. If fields
and fields are the same between two lines in the comparison
then the first of these sorts by position of each line (it's
a "stable sort") while the latter sorts by the content of the
dalke at dalkescientific.com
More information about the Python-list