python 日期排序
问题1:如果日期中有千年以前的情况(没法用格式化函数),如('2010-11-23','1989-3-7','2010-1-5','978-12-1','2010-2-4')参照方法1
问题2:如果日期中没有千年以前的情况,做法就很多了。参照方法2和方法3
1 # -*- coding: utf-8 -*- 2 import time 3 from operator import itemgetter 4 arr=('2010-11-23','1989-3-7','2010-1-5','978-12-1','2010-2-4') 5 def date_sort1(x): 6 ls=list(x) 7 #用了冒泡排序来排序,其他方法效果一样 8 for j in range(len(ls)-1): 9 for i in range(len(ls)-j-1): 10 lower=ls[i].split('-') 11 upper=ls[i+1].split('-') 12 for s in range(3): 13 if int(lower[s])>int(upper[s]): 14 ls[i],ls[i+1]=ls[i+1],ls[i] 15 break 16 elif int(lower[s])<int(upper[s]): 17 break 18 ar=tuple(ls) 19 return ar 20 ar=('2010-11-23','1989-3-7','2010-2-4','2010-1-5') 21 def date_sort2(x): 22 ls=list(x) 23 dic={} 24 for l in ls: 25 #返回用秒数来表示时间的浮点数 26 dic[l]=time.mktime(time.strptime(l, '%Y-%m-%d')) 27 28 dic=sorted(dic.iteritems(), key=itemgetter(1)) 29 sorted_items=[keys[0] for keys in dic] 30 ''' 31 items=dic.items() 32 backitems=[[v[1],v[0]] for v in items] 33 backitems.sort() 34 sorted_items=[keys[1] for keys in backitems] 35 ''' 36 ''' 37 items=dic.items() 38 backitems=[[v[0],v[1]] for v in items] 39 backitems=sorted(backitems, key=lambda x : x[1]) 40 sorted_items=[keys[0] for keys in backitems] 41 ''' 42 return tuple(sorted_items) 43 import datetime 44 def date_sort3(x): 45 ls=list(x) 46 #用了冒泡排序来排序,其他方法效果一样 47 for j in range(len(ls)-1): 48 for i in range(len(ls)-j-1): 49 lower=datetime.datetime.strptime(ls[i], '%Y-%m-%d') 50 upper=datetime.datetime.strptime(ls[i+1], '%Y-%m-%d') 51 if lower>upper: 52 ls[i],ls[i+1]=ls[i+1],ls[i] 53 return tuple(ls) 54 print date_sort1(arr) 55 print date_sort2(ar) 56 print date_sort3(ar)
运行结果:
('978-12-1', '1989-3-7', '2010-1-5', '2010-2-4', '2010-11-23')
('1989-3-7', '2010-1-5', '2010-2-4', '2010-11-23')
('1989-3-7', '2010-1-5', '2010-2-4', '2010-11-23')
正则表达式同样可以处理这类问题,下面是正则表达式的解决方案。
1 #利用正则表达式 2 import re 3 4 data = ['2010-11-23','1989-3-7','2010-1-5','978-12-1','2010-2-4'] 5 patt = '(\d+)-(\d+)-(\d+)' 6 #交换排序 7 for i in range(len(data)-1): 8 for x in range(i+1, len(data)): 9 j = 1 10 while j<4: 11 lower = re.match(patt, data[i]).group(j) 12 upper = re.match(patt, data[x]).group(j) 13 #print lower,upper 14 if int(lower) < int(upper): 15 j = 4 16 elif int(lower) == int(upper): 17 j += 1 18 else: 19 data[i],data[x] = data[x],data[i] 20 j = 4 21 print data