Python根据内嵌的数字将字符串排序(sort by numbers embedded in strings)
import re
re_digits = re.compile(r'(\d+)')
def embedded_numbers(s):
pieces = re_digits.split(s) # 切成数字与非数字
pieces[1::2] = map(int, pieces[1::2]) # 将数字部分转成整数
return pieces
def sort_strings_with_embedded_numbers(alist):
return sorted(alist, key=embedded_numbers)
files = '12 2 56 345 12'.split( )
new_list=sort_strings_with_embedded_numbers(files)
str=' '.join(new_list)
print(str)
import re
re_digits = re.compile(r'(\d+)')
def embedded_numbers(s):
pieces = re_digits.split(s) # 切成数字与非数字
pieces[1::2] = map(int, pieces[1::2]) # 将数字部分转成整数
return pieces
def sort_strings_with_embedded_numbers(alist):
return sorted(alist, key=embedded_numbers)
files = 'file3.txt file11.txt file7.txt file4.txt file15.txt'.split( )
new_list=sort_strings_with_embedded_numbers(files)
str=' '.join(new_list)
print(str)
chrfiles = [ 'chr9.txt', 'chr10.txt', 'chr1.txt', 'chr3.txt', 'chr11.txt' ]
chrfiles.sort(key = lambda x:int(re.match('\D+(\d+)\.txt',x).group(1)))
chrfiles
chrfiles = [ '9.txt', '10.txt', '1.txt', '3.txt', '11.txt' ]
chrfiles.sort(key = lambda x:int(re.match('(\d+)\.txt',x).group(1)))
chrfiles
chrfiles = [ '9', '10', '1', '3', '11' ]
chrfiles.sort(key = lambda x:int(re.match('(\d+)',x).group(1)))
chrfiles
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步