Code Point
September 10, 2010, 06:45:24 AM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
News: Geshi Sintax Hilighting Mod Installed. Tens of languages available.
 
   Home   Help Search Login Register  
Pages: [1]   Go Down
  Print  
Author Topic: Sort a list  (Read 2502 times)
Brussely
Jr. Member
*

Karma: 0
Offline Offline

Posts: 2


« on: September 14, 2006, 01:10:22 PM »

I'm trying to sort a list but it is not working:

Code
>>> l
['2', '2', '1', '4', '2', '21', '5', '2', '5', '1', '7', '2', '10']
>>> sorted(l)
['1', '1', '10', '2', '2', '2', '2', '2', '21', '4', '5', '5', '7']
Logged
Alter Lobo
Global Moderator
Jr. Member
*****

Karma: 10
Offline Offline

Posts: 65


« Reply #1 on: September 14, 2006, 01:28:33 PM »

It would work as you want if the list items were numbers. You have a number of ways to solve it for a list of strings.

If your Python is 2.4 use the key parameter to compare each item as an integer. This is the easiest:

Code
>>> sorted(l, key = int)
['1', '1', '2', '2', '2', '2', '2', '4', '5', '5', '7', '10', '21']

With any Python version you can use the cmp parameter to compare each two items with a user supplied comparison function:

Code
>>> sorted(l, cmp = lambda x,y: cmp(int(x), int(y)))
['1', '1', '2', '2', '2', '2', '2', '4', '5', '5', '7', '10', '21']

Or use list comprehensions:

Code
>>> sorted([int(x) for x in l])
[1, 1, 2, 2, 2, 2, 2, 4, 5, 5, 7, 10, 21]
>>>
>>> # if you want the items back as strings apply the str() function to each item after the sort:
...
>>> [str(x) for x in sorted([int(x) for x in l])]
['1', '1', '2', '2', '2', '2', '2', '4', '5', '5', '7', '10', '21']
Logged
Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!