自然顺序 php,PHP的natsort函数的Python模拟(使用“自然顺序...

参见英文答案 > Does Python have a built in function for string natural sort?????????????????????????????????????15个

我想知道在Python中是否有类似于PHP natsort函数的东西?

l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']

l.sort()

得到:

['image1.jpg', 'image12.jpg', 'image15.jpg', 'image3.jpg']

但我想得到:

['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']

UPDATE

def try_int(s):

"Convert to integer if possible."

try: return int(s)

except: return s

def natsort_key(s):

"Used internally to get a tuple by which s is sorted."

import re

return map(try_int, re.findall(r'(\d+|\D+)', s))

def natcmp(a, b):

"Natural string comparison, case sensitive."

return cmp(natsort_key(a), natsort_key(b))

def natcasecmp(a, b):

"Natural string comparison, ignores case."

return natcmp(a.lower(), b.lower())

l.sort(natcasecmp);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值