码迷,mamicode.com
首页 > 编程语言 > 详细

Python根据内嵌的数字将字符串排序(sort by numbers embedded in strings)

时间:2015-02-03 10:49:28      阅读:376      评论:0      收藏:0      [点我收藏+]

标签:

 

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!