简体   繁体   English

Python排序字​​符串以数字开头

[英]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. 谢谢。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM