Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 use re, I can do it. But it is not interesting. Do you guys have nice implementation ideas? I suppose python 3.x for this code.

names = [
'Test-1.model',
'Test-4.model',
'Test-6.model',
'Test-8.model',
'Test-10.model',
'Test-20.model'
]
number_sorted = get_number_sorted(names)
print(number_sorted)
'Test-20.model'
'Test-10.model'
'Test-8.model'
'Test-6.model'
'Test-4.model'
'Test-1.model'
like image 656
jef Avatar asked Jan 24 '18 01:01

jef


People also ask

How do you sort a string with a number inside?

To do this we can use the extra parameter that sort() uses. This is a function that is called to calculate the key from the entry in the list. We use regex to extract the number from the string and sort on both text and number.

Can you sort a list which contains both numeric and string data?

Definition and Usage Note: You cannot sort a list that contains BOTH string values AND numeric values.

How do you sort a list numerically in Python?

Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.


1 Answers

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

import re
def 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)
like image 133
jef Avatar answered Sep 17 '22 16:09

jef