1

I have a list looking like this:

pages= ['page34','page1','page12','page9','page11','page2','page10']

I have tested this:

pages.sorted()

and I got something "almost" ordered, but not ok:

>>> pages
['page1', 'page10', 'page11', 'page12', 'page2', 'page34', 'page9']

So, How could I get the desired ordered list, looking like:

page1, page2, page9, page10, page11, page12 and page34

codeKiller
  • 5,493
  • 17
  • 60
  • 115

1 Answers1

5

You can do that as:

pages = ['page34','page1','page12','page9','page11','page2','page10']

pages.sort(key = lambda x: int(x[4:]))

>>> print pages
['page1', 'page2', 'page9', 'page10', 'page11', 'page12', 'page34']

This will sort the list based on the numeric value of the page number (x[4:])

Suggested reading (by Grijesh Chauhan): https://wiki.python.org/moin/HowTo/Sorting

sshashank124
  • 31,495
  • 9
  • 67
  • 76