Sorting list (maybe stupid)

Charl P. Botha cpbotha at i_triple_e.org
Tue Jun 11 06:19:18 EDT 2002


In article <ae4hn9$jm4$1 at wanadoo.fr>, Eric Brunel wrote:
> Charl P. Botha wrote:
> 
>> In article <slrnagbh7m.h03.jarvin24 at lehtori.cc.tut.fi>, Jarvinen Petri
>> wrote:
>>> I have a problem and can't solve it:
>>> 
>>> There is lines of text like:
>>> 
>>> 2. Header2
>>> 1. Header1
>>> 102. Header102
>>> 
>>> and so on...
>>> 
>>> And I need to sort them according to the number (1,2,3,4...)
>> 
>> Put each line in a tuple, first element the number, second element the
>> header.  Make a list of these tuples, and then use list.sort() with a comp
>> function that compares using the first element in the tuple.
> 
> I think it's useless. Just try:

I would NOT use the word "useless" here.  You were thinking of
"unnecessary", probably.  Please don't go into politics, you are bound to
cause wars with your choice of words. ;)

> l = [(102, 'foo'), (2, 'bar'), (1, 'baz')]
> l.sort()
> print l
> 
> Apparently, the default sort function already sorts tuples according to 
> their first element...

Making an assumption based on this single example is very dangerous.
However, it seems you were lucky in this case.  See:
http://manatee.mojam.com/~skip/python/fastpython.html (the section on
Sorting).

-- 
charl p. botha http://cpbotha.net/ http://visualisation.tudelft.nl/



More information about the Python-list mailing list