标签:
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
Python根据内嵌的数字将字符串排序(sort by numbers embedded in strings)
标签:
原文地址:http://www.cnblogs.com/emanlee/p/4269158.html