![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programmer
Join Date: Jun 2005
Posts: 68
Rep Power: 4
![]() |
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. |
|
|
|
|
|
#2 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
>>> int("23")
23
>>> "23" * 2
'2323'
>>> int("23") * 2
46
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
|
#3 |
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5
![]() |
Some additional useful code:
python Syntax (Toggle Plain Text)
|
|
|
|
|
|
#4 |
|
Programmer
Join Date: Jun 2005
Posts: 68
Rep Power: 4
![]() |
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.
|
|
|
|
|
|
#5 |
|
Programmer
|
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'] |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Update IdTCPSDerver in a DLL | sggaunt | Delphi | 0 | Mar 13th, 2007 12:56 PM |
| VB Phone Number to Name... | NDawg28 | Visual Basic | 9 | Mar 10th, 2007 10:40 PM |
| Sorting lists | Sane | Python | 21 | May 5th, 2005 7:39 PM |
| Linking dll failure (file not found) | amrfathy_egy | Visual Basic | 8 | Feb 3rd, 2005 4:13 AM |