Clever way of sorting strings containing integers?

bieffe62 at gmail.com bieffe62 at gmail.com
Thu Oct 9 04:57:54 EDT 2008


On 9 Ott, 09:41, Holger <ish... at gmail.com> wrote:
> I tried to do this elegantly, but did not come up with a good solution
>
> Sort strings like
> foo1bar2
> foo10bar10
> foo2bar3
> foo10bar2
>
> So that they come out:
> foo1bar2
> foo2bar3
> foo10bar2
> foo10bar10
>
> I.e. isolate integer parts and sort them according to integer value.
>
> Thx
> Holger

This should work, if you have all stribngs in memory:

import re
REXP = re.compile( r'\d+' )
lines = ['foo1bar2', 'foo10bar10', 'foo2bar3', 'foo10bar2' ]
def key_function( s ): return map(int, re.findall(REXP, s ))
lines.sort( key=key_function)


Ciao
----
FB





More information about the Python-list mailing list