Sort string list by a number in string? Sort string list by a number in string? python-3.x python-3.x

Sort string list by a number in string?


the key is ... the key

sorted(names, key=lambda x: int(x.partition('-')[2].partition('.')[0]))

Getting that part of the string recognized as the sort order by separating it out and transforming it to an int.


Some alternatives:

(1) Slicing by position:

sorted(names, key=lambda x: int(x[5:-6]))

(2) Stripping substrings:

sorted(names, key=lambda x: int(x.replace('Test-', '').replace('.model', '')))

(3) Splitting characters (also possible via str.partition):

sorted(names, key=lambda x: int(x.split('-')[1].split('.')[0]))

(4) Map with np.argsort on any of (1)-(3):

list(map(names.__getitem__, np.argsort([int(x[5:-6]) for x in names])))


I found a similar question and a solution by myself.Nonalphanumeric list order from os.listdir() in Python

import redef sorted_alphanumeric(data):    convert = lambda text: int(text) if text.isdigit() else text.lower()    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]     return sorted(data, key=alphanum_key, reverse=True)