Sort list of strings by integer suffix
I have a list of strings:
[song_1, song_3, song_15, song_16, song_4, song_8]
I would like to sort them by the # at the end, unfortunately since the lower numbers aren't "08" and are "8", they are treated as larger than 15 in lexicographical order.
I know I have to pass a key to the sort function, I saw this somewhere on this site to sort decimal numbers that are strings:
sorted(the_list, key=lambda a:map(int,a.split('.'))
But that was for "1.2, 2.5, 2.3" but I don't have that case. I thought of replacing '开发者_JS百科.' with '_' but from what I understand it converts both sides to int
s, which will fail since the left side of the _ is a string.
EDIT: I forgot to mention that all the prefixes are the same (song in this example)
You're close.
sorted(the_list, key = lambda x: int(x.split("_")[1]))
should do it. This splits on the underscore, takes the second part (i.e. the one after the first underscore), and converts it to integer to use as a key.
Well, you want to sort by the filename first, then on the int part:
def splitter( fn ):
try:
name, num = fn.rsplit('_',1) # split at the rightmost `_`
return name, int(num)
except ValueError: # no _ in there
return fn, None
sorted(the_list, key=splitter)
sorted(the_list, key = lambda k: int(k.split('_')[1]))
def number_key(name):
parts = re.findall('[^0-9]+|[0-9]+', name)
L = []
for part in parts:
try:
L.append(int(part))
except ValueError:
L.append(part)
return L
sorted(your_list, key=number_key)
精彩评论