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

Philippe C. Martin philippe at philippecmartin.com
Thu Apr 28 14:01:16 EDT 2005


How about using the csv module instead of splitting ?


wittempj at hotmail.com wrote:

> 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