如果“2010-09-11”是年-月-日,您可以:somedata = 'jyhghg'
t = [('2010-09-11','somedata',somedata),
('2010-06-11','somedata',somedata),
('2010-09-12','somedata',somedata),
('2010-08-12','somedata',somedata)]
from operator import itemgetter
t.sort(key = itemgetter(0))
print t
结果
^{pr2}$
一。在
如果“2010-09-11”是年-日-月,您可以:from time import strptime,strftime
somedata = 'jyhghg'
t = [('2010-09-11','somedata',somedata),
('2010-06-11','somedata',somedata),
('2010-09-12','somedata',somedata),
('2010-08-12','somedata',somedata)]
t.sort(key = lambda x: strftime('%Y%m%d',strptime(x[0],'%Y-%d-%m')))
print t
结果[('2010-06-11', 'somedata', 'jyhghg'),
('2010-09-11', 'somedata', 'jyhghg'),
('2010-08-12', 'somedata', 'jyhghg'),
('2010-09-12', 'somedata', 'jyhghg')]
一。在
编辑1
读了Artsiom Rudzenka的答案,他在书中单独使用了strptime(),我意识到strptime()生成了一个按性质排序的struct\u time对象。这样的对象具有属性tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst,可以通过公共点表示法访问(总经理例如),但也可以通过索引符号访问(例如,toto[1],因为struc\u time对象的属性是按tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst的顺序注册的。struct-time数据类型有一个名为tuple的接口。在
由于struct\u time对象是按性质排序的,因此不必应用strftime()来获得按此顺序具有year-month-day的日期字符串:此顺序已存在于struct\u time对象中。在
然后,我更正了2010-06-11中11是月份的情况下的代码:我消除strftime()from time import strptime
somedata = 'jyhghg'
t = [('2010-09-11','somedata',somedata),
('2010-06-11','somedata',somedata),
('2010-09-12','somedata',somedata),
('2010-08-12','somedata',somedata)]
t.sort(key = lambda x: strptime(x[0],'%Y-%d-%m'))
print t
编辑2
考虑到柯克·斯特劳泽的信息:import re
regx = re.compile('(\d{4})-(\d\d)-(\d\d)')
somedata = 'jyhghg'
t = [('2010-09-11','somedata',somedata),
('2010-06-11','somedata',somedata),
('2010-09-12','somedata',somedata),
('2010-08-12','somedata',somedata)]
t.sort(key = lambda x: regx.match(x[0]).group(1,3,2))
print t