how can I sort a bunch of lists over multiple fields?

wittempj@hotmail.com martin.witte at gmail.com
Wed Apr 27 14:06:12 EDT 2005


What you want I guess is to read first all lines of the file into a
string as you did, and then let the split method split it based on
newlines only - see example below.

Then you use split again to put all elements of one line into another
list - split it on commas.

Now you can define sortfunctions for all columns you want to sort, e.g.
like below - and use those to compare elements. You get a script like:
-#!/usr/bin/env python
-
-def cmp_index(a, b, ndx):
-   if a[ndx] < b[ndx]:
-        return -1
-    elif a[ndx] > b[ndx]:
-       return 1
-    else:
-        return 0
-
-def cmp_0(a, b):
-    return cmp_index(a, b, 0)
-
-def cmp_1(a, b):
-    return cmp_index(a, b, 1)
-
-s = 'Kikker en Eend,Max Veldhuis\nDikkie Dik,Jet Boeke\nRuminations on
C++,Andrew Koenig & Barbara Moo'
-s = s.split('\n')
-l = []
-for i in s:
-    l.append(i.split(','))
-
-l.sort(cmp_0)
-print l
-l.sort(cmp_1)
-print l

with output like:
martin at ubuntu:~ $ ./test.py
[['Dikkie Dik', 'Jet Boeke'], ['Kikker en Eend', 'Max Veldhuis'],
['Ruminations on C++', 'Andrew Koenig & Barbara Moo']]
[['Ruminations on C++', 'Andrew Koenig & Barbara Moo'], ['Dikkie Dik',
'Jet Boeke'], ['Kikker en Eend', 'Max Veldhuis']]
martin at ubuntu:~ $




More information about the Python-list mailing list