python - Sorting a list and dict keys -


i'm using python 2.7 , have list:

photos = ['arthur20.jpg', 'arthur7.jpg', 'arthur11.jpg', 'arthur3.jpg', 'arthur5.jpg', 'arthur17.jpg', 'arthur15.jpg', 'arthur2.jpg', 'arthur13.jpg', 'arthur8.jpg', 'arthur9.jpg', 'arthur18.jpg', 'arthur4.jpg', 'arthur6.jpg', 'arthur10.jpg', 'arthur12.jpg', 'arthur14.jpg', 'arthur19.jpg', 'arthur16.jpg', 'arthur1.jpg'] 

how can organize list? tried use sort() didn't work, returned me this:

['arthur1.jpg', 'arthur10.jpg', 'arthur11.jpg', 'arthur12.jpg', 'arthur13.jpg', 'arthur14.jpg', 'arthur15.jpg', 'arthur16.jpg', 'arthur17.jpg', 'arthur18.jpg', 'arthur19.jpg', 'arthur2.jpg', 'arthur20.jpg', 'arthur3.jpg', 'arthur4.jpg', 'arthur5.jpg', 'arthur6.jpg', 'arthur7.jpg', 'arthur8.jpg', 'arthur9.jpg'] 

and strings of list keys dict , have put keys in order too, this:

dict = {"arthur1.jpg":1, "arthur2.jpg":2 ...} 

sort() sort list in natural ordering, in case - lexicographical ordering. can sort number following "arthur" custom sort function. easiest way this, imho, extract number using regular expression:

import re photos.sort(key = lambda x : int(re.findall('\d+', x)[0])) 

once have list sorted, creating dict want matter of ziping:

from collections import ordereddict dict = ordereddict(zip(photos, range(1, len(photos) + 1))) 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -