-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.

2
  • 2
    Lexicographical ordering or ordering by numbers? Commented Nov 21, 2013 at 21:25
  • 3
    What have you tried? Have you read the docs on list.sort and sorted? Commented Nov 21, 2013 at 21:27

3 Answers 3

4

Try the sorted() function:

>>> sortedList = sorted([u'test3',u'test2',u'test5'])
>>> print sortedList
[u'test2', u'test3', u'test5']
Sign up to request clarification or add additional context in comments.

Comments

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']

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.