Clever way of sorting strings containing integers?
Holger
ishoej at gmail.com
Thu Oct 9 05:18:48 EDT 2008
On 9 Okt., 10:57, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
> On Thu, 09 Oct 2008 00:41:27 -0700, Holger 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.
>
> import re
>
> def key_func(string):
> result = re.split(r'(\d+)', string)
> for i in xrange(1, len(result), 2):
> result[i] = int(result[i])
> return result
>
> def main():
> lines = ['foo1bar2',
> 'foo10bar10',
> 'foo2bar3',
> 'foo10bar2',
> 'fo',
> 'bar1000',
> '777']
> lines.sort(key=key_func)
> print '\n'.join(lines)
Perfect!
Thank you.
More information about the Python-list
mailing list