0

I have this list of files:

1.jpg, 2.jpg, ..., 10.jpg, ...

If I do a python os.listdir(".") i have all files listed but in alphabetical order like this:

[1.jpg, 10.jpg, 11.jpg, ..., 2.jpg, 20.jpg....]

But I want them ordered by its numerical value

[1.jpg, 2.jpg ,...10 ,11 ,12... ]

How do I reorder the list to have this done?

tx

butelo
  • 1,653
  • 1
  • 18
  • 29
  • see also http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort, http://stackoverflow.com/questions/2545532/python-analog-of-natsort-function-sort-a-list-using-a-natural-order-algorithm, http://stackoverflow.com/questions/11150239/python-natural-sorting, http://stackoverflow.com/questions/6849047/naturally-sort-a-list-of-alpha-numeric-tuples-by-the-tuples-first-element-in-py and 1999+ similar questions. – georg Oct 30 '12 at 19:29

1 Answers1

6
In [51]: lis=["1.jpg","10.jpg","11.jpg","2.jpg","20.jpg"]

In [52]: sorted(lis,key=lambda x:int(x.split(".")[0]))
Out[52]: ['1.jpg', '2.jpg', '10.jpg', '11.jpg', '20.jpg']
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504