Sort String List By A Number In String?
I have the following string list. Then, I want to sort it by a number in each element. sorted failed because it cannot handle the order such as between 10 and 3. I can imagine if I
Solution 1:
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.
Solution 2:
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])))
Solution 3:
I found a similar question and a solution by myself. Nonalphanumeric list order from os.listdir() in Python
import re
defsorted_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) ]
returnsorted(data, key=alphanum_key, reverse=True)
Solution 4:
You can use re.findall
in with the key
of the sort function:
import re
names = [
'Test-1.model',
'Test-4.model',
'Test-6.model',
'Test-8.model',
'Test-10.model',
'Test-20.model'
]
final_data = sorted(names, key=lambda x:int(re.findall('(?<=Test-)\d+', x)[0]), reverse=True)
Output:
['Test-20.model', 'Test-10.model', 'Test-8.model', 'Test-6.model', 'Test-4.model', 'Test-1.model']
Solution 5:
def find_between( s, first, last ):
try:
start= s.index( first ) + len( first )
end= s.index( last, start )
return s[start:end]
except ValueError:
return ""
and then do something like
sorted(names, key=lambda x: int(find_between(x, 'Test-', '.model')))
Post a Comment for "Sort String List By A Number In String?"