1

Sorry for boring question but I can't figure this out:

for f in sorted(os.listdir('.')): print f

Output:

p1.html
p10.html
p11.html
p12.html
p13.html
p14.html
p15.html
p16.html
p17.html
p18.html
p19.html
p2.html
p20.html
p21.html
p22.html
p3.html
p4.html
...

Obviously I want to sort by number and I can do it with this key: f.split('.')[0][1:] but how to reference that key in this for loop?

I tried for f in sorted(os.listdir('.'), key=f.split('.')[0][1:]) but it does not work of course

TIA

otrov
  • 13
  • 2

1 Answers1

1

You'd need a lambda expression:

sorted(os.listdir('.'), key=lambda f: int(f.split('.')[0][1:]))
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 1
    He's probably looking for a numerical sort... so IMO it should be `lambda f:int(f.split('.')[0][1:])` – 6502 Apr 02 '11 at 21:45