Python Sort Strings Started With Digits
I have the next list: a = ['1th Word', 'Another Word', '10th Word'] print a.sort() >>> ['10th Word', '1th Word', 'Another Word'] But I need: ['1th Word', '10th Word','Ano
Solution 1:
Here's a function that works for the general case
import re
defnatkey(s):
return [int(p) if p else q for p, q in re.findall(r'(\d+)|(\D+)', s)]
x = ['1th Word', 'Another Word 2x', 'Another Word 20x', '10th Word 10', '2nd Word']
printsorted(x)
printsorted(x, key=natkey)
Result:
['10th Word 10', '1th Word', '2nd Word', 'Another Word 20x', 'Another Word 2x']['1th Word', '2nd Word', '10th Word 10', 'Another Word 2x', 'Another Word 20x']
Solution 2:
This is commonly called "natural sort".
See Does Python have a built in function for string natural sort? and Python analog of natsort function (sort a list using a "natural order" algorithm); also http://code.activestate.com/recipes/285264-natural-string-sorting/ and http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html.
Solution 3:
r = re.compile(r'(\d+)')
defsort_by_number(s):
m = r.match(s)
return m and m.group(0) or s
x.sort(key=sort_by_number)
Key is that if there was not match, return the string as is
Post a Comment for "Python Sort Strings Started With Digits"