[英]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','Another Word']
Is there an easy way to do this? 是否有捷径可寻?
I tried: 我试过了:
r = re.compile(r'(\d+)')
def sort_by_number(s):
m = r.match(s)
return m.group(0)
x.sort(key=sort_by_number)
But some strings do not have numbers and this leads to an errors. 但是某些字符串没有数字,这会导致错误。 Thanks.
谢谢。
This is commonly called "natural sort". 这通常称为“自然排序”。
See Does Python have a built in function for string natural sort? 请参阅Python是否具有用于字符串自然排序的内置函数? and Python analog of natsort function (sort a list using a "natural order" algorithm) ;
和natsort函数的Python类似物(使用“自然顺序”算法对列表进行排序) ; 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 .
还有http://code.activestate.com/recipes/285264-natural-string-sorting/和http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order。 html 。
Here's a function that works for the general case 这是一个适用于一般情况的函数
import re
def natkey(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']
print sorted(x)
print sorted(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']
r = re.compile(r'(\d+)')
def sort_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 关键是如果不匹配,则按原样返回字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.