-3

I am trying to sort list in Python in the ascending order.

Below is my code -

children=zk.get_children("/my/example", watch=my_func)
print(children)

So the above print statement will print out something like this -

[u'test2', u'test1', u'test3']

or

[u'test3', u'test2', u'test1']

or in any order..

Now I need to make sure that after sorting it should look like this in the ascending order

[u'test1', u'test2', u'test3']

Any thoughts how this can be done efficiently in Python?

NOTE: name will always be starting with test and then followed by some number.

AKIWEB
  • 19,008
  • 67
  • 180
  • 294
  • 2
    Lexicographical ordering or ordering by numbers? – Maciej Gol Nov 21 '13 at 21:25
  • 3
    What have you tried? Have you read the docs on [`list.sort`](http://docs.python.org/2/library/stdtypes.html#mutable-sequence-types) and [`sorted`](http://docs.python.org/2/library/functions.html#sorted)? – Lev Levitsky Nov 21 '13 at 21:27

3 Answers3

4

Try the sorted() function:

>>> sortedList = sorted([u'test3',u'test2',u'test5'])
>>> print sortedList
[u'test2', u'test3', u'test5']
wnnmaw
  • 5,444
  • 3
  • 38
  • 63
4

Assuming you want to sort the arrays by the test number, you can just pass sorted a key function that will extract the number at the end of each 'test':

>>> tests = [ "test%s" % i for i in range(1, 15) ]
>>> sorted(tests, key=lambda t: int(t[4:]))
['test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8',
 'test9', 'test10', 'test11', 'test12', 'test13', 'test14']
mdml
  • 22,442
  • 8
  • 58
  • 66
2

What you need is a natural sort:

import re

convert = lambda text: int(text) if text.isdigit() else text.lower() 
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 

def natural_sort(l): 
    return sorted(l, key=alphanum_key)

and then you do

lst.sort(key=natural_sort)

If you want it reversed, then add reverse=True argument. If you don't want to sort in place (but create a new list) then use sorted(lst, key=natural_sort) instead.

freakish
  • 54,167
  • 9
  • 132
  • 169