I know that this sounds trivial but I did not realize that the sort()
function of Python was weird. I have a list of "numbers" that are actually in string form, so I first convert them to ints, then attempt a sort.
list1=["1","10","3","22","23","4","2","200"]
for item in list1:
item=int(item)
list1.sort()
print list1
Gives me:
['1', '10', '2', '200', '22', '23', '3', '4']
What I want is
['1','2','3','4','10','22','23','200']
I've looked around for some of the algorithms associated with sorting numeric sets, but the ones I found all involve sorting alphanumeric sets.
I know this is probably a no brainer problem but google and my textbook don't offer anything more or less useful than the .sort()
function.
This worked for me using python version 3, though it didn't in version 2.
You could pass a function to the
key
parameter to the.sort
method. With this, the system will sort by key(x) instead of x.BTW, to convert the list to integers permanently, use the
map
functionor list comprehension
The most recent solution is right. You are reading solutions as a string, in which case the order is 1, then 100, then 104 followed by 2 then 21, then 2001001010, 3 and so forth.
You have to CAST your input as an int instead:
sorted strings:
stringList = (1, 10, 2, 21, 3)
sorted ints:
intList = (1, 2, 3, 10, 21)
To cast, just put the stringList inside int ( blahblah ).
Again:
You haven't actually converted your strings to ints. Or rather, you did, but then you didn't do anything with the results. What you want is:
However, python makes it even easier for you: sort takes a named parameter, key, which is a function that is called on each element before it is compared (but without modifying the list)
if you want to use string of the numbers better take another list as shown in my code it will work fine.
Seamus Campbell's answer doesnot work on python2.x.
list1 = sorted(list1, key=lambda e: int(e))
usinglambda
function works well.