tabular data
Siggy Brentrup
bsb at winnegan.de
Sun Apr 9 02:16:40 EDT 2000
poupaerte at my-deja.com writes:
> Hi
>
[...]
> For example, say that I have the following tabular data: [(2,1,"REC02"),
> (1,3,"REC03"),(3,1,"REC01")], and I want to obtain: [(1,3,"REC03"),
> (2,1,"REC02"),(3,1,"REC01")], that is, the tabular data should be
> sorted on the first and then the second column.
> How can I have Python perform an in-place sort on a combination of
> several columns?
Simply use the list's sort() method, it does a lex sort:
Python 1.5.2 (#0, Apr 3 2000, 14:46:48) [GCC 2.95.2 20000313 (Debian GNU/Linux)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> l = [(2,1,"REC02"),(1,3,"REC03"),(3,1,"REC01")]
>>> l.sort()
>>> l
[(1, 3, 'REC03'), (2, 1, 'REC02'), (3, 1, 'REC01')]
>>> l.append((1,2,'REC4'))
>>> l.sort()
>>> l
[(1, 2, 'REC4'), (1, 3, 'REC03'), (2, 1, 'REC02'), (3, 1, 'REC01')]
>>> # You may even specify a comparision function
>>> l.sort(lambda a,b: cmp((a[1],a[0]),(b[1],b[0])))
>>> l
[(2, 1, 'REC02'), (3, 1, 'REC01'), (1, 2, 'REC4'), (1, 3, 'REC03')]
> By the way, should I represent rows by tuples or by embedded lists?
See the thread "Tuples -- who needs 'en"
[Gordon McMillan]
| Lists are collections. The competing choice to a list is a
| dictionary. Tuples are toy structs; the competing choice is a class.
[...]
Regards
Siggy
--
Siggy Brentrup - bsb at winnegan.de - http://www.winnegan.de/
bsb at north.de - http://www.north.de/~bsb/
****** ceterum censeo javascriptum esse restrictam *******
More information about the Python-list
mailing list