Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Python (http://www.programmingforums.org/forum43.html)
-   -   Sorting integer lists (http://www.programmingforums.org/showthread.php?t=14067)

sixstringartist Sep 30th, 2007 3:57 PM

Sorting integer lists
 
Im studying python and I am unsure of how to solve a problem.

Im taking user input of two strings consisting of integers. I split these on whitespace into two lists, merge the lists, and sort it. My problem is that these lists are being sorted by character and not integers (i.e. 22 > 3).

Ive searched for a solution to this but have yet to find one. Does Python know these are characters? Can I convert each value, element-by-element into integers and expect it to sort them numerically?

Thanks.

DaWei Sep 30th, 2007 4:50 PM

:

>>> int("23")
23
>>> "23" * 2
'2323'
>>> int("23") * 2
46


Arevos Oct 1st, 2007 1:26 PM

Some additional useful code:

:

  1. >>> xs = ["2", "13", "3"]
  2. >>> xs.sort()
  3. >>> xs
  4. ['13', '2', '3']
  5.  
  6. >>> ys = map(int, xs)
  7. >>> ys
  8. [13, 2, 3]
  9. >>> ys.sort()
  10. >>> ys
  11. [2, 3, 13]
  12.  
  13. >>> zs = [int(i) for i in x]
  14. >>> zs
  15. [13, 2, 3]
  16. >>> zs.sort()
  17. [2, 3, 13]


sixstringartist Oct 5th, 2007 5:08 PM

Thanks DaWei but I was already aware that the issue was with they type of data in the list. What I was looking for was an approach like Arevos posted. I resorted to converting each value one by one to an int, but I was looking for a built-in way. It seems "map()" is what I was looking for. I'll read more about it.

somehollis Dec 4th, 2007 3:27 PM

Re: Sorting integer lists
 
I realize this thread is rather old, but for reference, you can also use your list's sort() method if you add a parameter to it.
:

numList = ["12","4","66","55"]
numList.sort(cmp = lambda x,y: int(x) - int(y))
# returns ['4','12','55',66']



All times are GMT -5. The time now is 3:09 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC