How to sort the line with the number inside?

Possible duplicate:
Does Python have a built-in function for naturally sorting strings?

I have a list of strings containing numbers, and I cannot find a good way to sort them.
For example, I get something like this:

something1 something12 something17 something2 something25 something29 

using the sort() method.

I know that I probably need to somehow extract the numbers and then sort the list, but I have no idea how to do this in the easiest way.

+78
python string sorting regex
May 11 '11 at 16:21
source share
1 answer

You might be looking for sorting people (also known as natural sorting ):

 import re def atoi(text): return int(text) if text.isdigit() else text def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy implementation in the comments) ''' return [ atoi(c) for c in re.split(r'(\d+)', text) ] alist=[ "something1", "something12", "something17", "something2", "something25", "something29"] alist.sort(key=natural_keys) print(alist) 

profitability

 ['something1', 'something2', 'something12', 'something17', 'something25', 'something29'] 

PS. I modified my answer to use the Toothy natural sort implementation (posted in the comments here ), as it is significantly faster than my original answer.




If you want to sort the text using floating-point numbers, then you need to change the regular expression to match (for example, (\d+) ) to a floating-point regular expression :

 import re def atof(text): try: retval = float(text) except ValueError: retval = text return retval def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy implementation in the comments) float regex comes from /questions/23485/regular-expression-for-floating-point-numbers/173679#173679 ''' return [ atof(c) for c in re.split(r'[+-]?([0-9]+(?:[.][0-9]*)?|[.][0-9]+)', text) ] alist=[ "something1", "something2", "something1.0", "something1.25", "something1.105"] alist.sort(key=natural_keys) print(alist) 

profitability

 ['something1', 'something1.0', 'something1.105', 'something1.25', 'something2'] 
+157
May 11 '11 at 16:24
source share



All Articles