Specify a key
parameter to sorted
to tell it how to sort the strings that's different from standard alphabetical comparison.
>>> files = [
... "yourlieinapril1/frame1094.jpg",
... "yourlieinapril1/frame1095.jpg",
... "yourlieinapril1/frame1096.jpg",
... "yourlieinapril1/frame1097.jpg",
... "yourlieinapril1/frame1098.jpg",
... "yourlieinapril1/frame1099.jpg",
... "yourlieinapril1/frame1100.jpg",
... "yourlieinapril1/frame110.jpg",
... "yourlieinapril1/frame1101.jpg",
... ]
>>> sorted(files, key=lambda s: int(s[21:-4]))
['yourlieinapril1/frame110.jpg', 'yourlieinapril1/frame1094.jpg', 'yourlieinapril1/frame1095.jpg', 'yourlieinapril1/frame1096.jpg', 'yourlieinapril1/frame1097.jpg', 'yourlieinapril1/frame1098.jpg', 'yourlieinapril1/frame1099.jpg', 'yourlieinapril1/frame1100.jpg', 'yourlieinapril1/frame1101.jpg']
If your real data set is more complicated (i.e. the leading non-numeric part is variable and you want to sort on that plus the numeric value), your key
function might instead do something like returning a tuple of the leading str
and the trailing int
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…