sorting a list numbers stored as strings

A

aine_canby

hi,

I have the following list -

["1", "11", "2", "22"]

how do I sort it like this -

["1", "2", "11", "22"]

thanks,

aine
 
B

Bruno Desthuilliers

(e-mail address removed) a écrit :
hi,

I have the following list -

["1", "11", "2", "22"]

how do I sort it like this -

["1", "2", "11", "22"]

source = ["1", "11", "2", "22"]
result = [t[1] for t in sorted((int(item), item) for item in source)]
print result
 
C

Carsten Haese

hi,

I have the following list -

["1", "11", "2", "22"]

how do I sort it like this -

["1", "2", "11", "22"]

Hi,
l = ["1", "11", "2", "22"]
sorted(l, cmp = lambda x, y: cmp(int(x), int(y))) # provide your own compare function !
l
['1', '2', '11', '22']

That interpreter session is a work of fiction, since sorted returns the
sorted list instead of sorting the list in place. Also, it's better
(i.e. more readable and likely faster) to use a sort key function
instead of a comparison function whenever possible. In this case, the
sort key function is particularly trivial:
l = ["1", "11", "2", "22"]
sorted(l, key=int)
['1', '2', '11', '22']
 
P

Peter Otten

aine_canby said:
I have the following list -

["1", "11", "2", "22"]

how do I sort it like this -

["1", "2", "11", "22"]
items = ["1", "11", "2", "22"]
items.sort(key=int)
items
['1', '2', '11', '22']

This is more efficient than Amit's compare function and even Bruno's
decorate-sort-undecorate (DSU) -- which of course only matters if the list
becomes a bit larger.

Peter
 
A

Amit Khemka

l = ["1", "11", "2", "22"]
sorted(l, cmp = lambda x, y: cmp(int(x), int(y))) # provide your own compare function !
l
['1', '2', '11', '22']

That interpreter session is a work of fiction, since sorted returns the
sorted list instead of sorting the list in place.

I am sorry, thanks for pointing out !
What I intended to write was:

Btw, It was more of a goofed up Reality show !

cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top