python对数字末尾的字符串进行排序 [英] python sort strings with digits at the end

查看:379
本文介绍了python对数字末尾的字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最简单的方法是用数字结尾对字符串列表进行排序,其中有些数字为3位,有些数字为4:

what is the easiest way to sort a list of strings with digits at the end where some have 3 digits and some have 4:

>>> list = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> list.sort()
>>> print list
['asdf111', 'asdf123', 'asdf1234', 'asdf124']

应将1234放在最后.有没有简单的方法可以做到这一点?

should put the 1234 one on the end. is there an easy way to do this?

推荐答案

有一种简单的方法吗?

is there an easy way to do this?

目前还不清楚真正的规则是什么. 有些有3位数字,有些有4位数字"并不是一个非常精确或完整的规范.您所有的示例在数字前均显示4个字母.总是这样吗?

It's perfectly unclear what the real rules are. The "some have 3 digits and some have 4" isn't really a very precise or complete specification. All your examples show 4 letters in front of the digits. Is this always true?

import re
key_pat = re.compile(r"^(\D+)(\d+)$")
def key(item):
    m = key_pat.match(item)
    return m.group(1), int(m.group(2))

key函数可能会执行您想要的操作.否则可能太复杂了.也许模式真的是r"^(.*)(\d{3,4})$",或者规则甚至更晦涩.

That key function might do what you want. Or it might be too complex. Or maybe the pattern is really r"^(.*)(\d{3,4})$" or maybe the rules are even more obscure.

>>> data= ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> data.sort( key=key )
>>> data
['asdf111', 'asdf123', 'asdf124', 'asdf1234']

这篇关于python对数字末尾的字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆