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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。