时间:2022-03-22 10:36:14 | 栏目:Python代码 | 点击:次
问题1:如果日期中有千年以前的情况(没法用格式化函数),如('2010-11-23','1989-3-7','2010-1-5','978-12-1','2010-2-4')
参照方法1
问题2:如果日期中没有千年以前的情况,做法就很多了。参照方法2和方法3
# -*- coding: utf-8 -*- import time from operator import itemgetter arr=('2010-11-23','1989-3-7','2010-1-5','978-12-1','2010-2-4') def date_sort1(x): ls=list(x) #用了冒泡排序来排序,其他方法效果一样 for j in range(len(ls)-1): for i in range(len(ls)-j-1): lower=ls[i].split('-') upper=ls[i+1].split('-') for s in range(3): if int(lower[s])>int(upper[s]): ls[i],ls[i+1]=ls[i+1],ls[i] break elif int(lower[s])<int(upper[s]): break ar=tuple(ls) return ar ar=('2010-11-23','1989-3-7','2010-2-4','2010-1-5') def date_sort2(x): ls=list(x) dic={} for l in ls: #返回用秒数来表示时间的浮点数 dic[l]=time.mktime(time.strptime(l, '%Y-%m-%d')) dic=sorted(dic.iteritems(), key=itemgetter(1)) sorted_items=[keys[0] for keys in dic] ''' items=dic.items() backitems=[[v[1],v[0]] for v in items] backitems.sort() sorted_items=[keys[1] for keys in backitems] ''' ''' items=dic.items() backitems=[[v[0],v[1]] for v in items] backitems=sorted(backitems, key=lambda x : x[1]) sorted_items=[keys[0] for keys in backitems] ''' return tuple(sorted_items) import datetime def date_sort3(x): ls=list(x) #用了冒泡排序来排序,其他方法效果一样 for j in range(len(ls)-1): for i in range(len(ls)-j-1): lower=datetime.datetime.strptime(ls[i], '%Y-%m-%d') upper=datetime.datetime.strptime(ls[i+1], '%Y-%m-%d') if lower>upper: ls[i],ls[i+1]=ls[i+1],ls[i] return tuple(ls) print date_sort1(arr) print date_sort2(ar) 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')
正则表达式同样可以处理这类问题,下面是正则表达式的解决方案。
#利用正则表达式 import re data = ['2010-11-23','1989-3-7','2010-1-5','978-12-1','2010-2-4'] patt = '(\d+)-(\d+)-(\d+)' #交换排序 for i in range(len(data)-1): for x in range(i+1, len(data)): j = 1 while j<4: lower = re.match(patt, data[i]).group(j) upper = re.match(patt, data[x]).group(j) #print lower,upper if int(lower) < int(upper): j = 4 elif int(lower) == int(upper): j += 1 else: data[i],data[x] = data[x],data[i] j = 4 print data
总结