1

我需要按日期对列表列表进行排序:

mylist=['ML-M01 Qual Report 07/31/13', 'ML36220010 Complete Qual Testing 07/24/13', 'ML36220045 Final FRB 07/13/13', 'ML9822D2600 Brief to PM 08/5/13']

从这个网站,我得到了这个代码:

sorted(mylist, key=lambda x: datetime.datetime.strptime(x[2], '%m/%d/%y'))

但是,我收到此错误消息:

sorted(mylist,key=lambda x: datetime.datetime.strptime(x[2], '%m/%d/%y'))
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    sorted(mylist,key=lambda x: datetime.datetime.strptime(x[2], '%m/%d/%y'))
  File "<pyshell#25>", line 1, in <lambda>
  sorted(mylist,key=lambda x: datetime.datetime.strptime(x[2], '%m/%d/%y'))
  File "C:\Python25\Lib\_strptime.py", line 330, in strptime
    (data_string, format))
ValueError: time data did not match format:  data=-  fmt=%m/%d/%y

需要帮助 - 需要按 3d 元素对列表进行排序 - 最旧到最新

4

2 回答 2

8

列表中的每个条目都是字符串,而不是列表,x[2]单个字符也是如此('-'对于您的第一个条目)。您只需将日期部分拆分为strptime()

sorted(mylist, key=lambda x: datetime.datetime.strptime(x.rsplit(None, 1)[-1], '%m/%d/%y'))

为了提高效率,str.rsplit()对空格进行了一次拆分:

>>> 'ML-M01 Qual Report 07/31/13'.rsplit(None, 1)
['ML-M01 Qual Report', '07/31/13']
>>> 'ML-M01 Qual Report 07/31/13'.rsplit(None, 1)[-1]
'07/31/13'

结果:

>>> sorted(mylist, key=lambda x: datetime.datetime.strptime(x.rsplit(None, 1)[-1], '%m/%d/%y'))
['ML36220045 Final FRB 07/13/13', 'ML36220010 Complete Qual Testing 07/24/13', 'ML-M01 Qual Report 07/31/13', 'ML9822D2600 Brief to PM 08/5/13']

注意sorted()返回一个新的排序列表,原列表不受影响。如果要mylist就地排序,请调用其list.sort()上的方法:

mylist.sort(key=lambda x: datetime.datetime.strptime(x.rsplit(None, 1)[-1], '%m/%d/%y'))
于 2013-06-18T12:47:21.880 回答
2

你的错误:

ValueError: time data did not match format:  data=-  fmt=%m/%d/%y

表示您获得的数据"-"不是日期。这表明您的列表中有不包含有效日期的行。

此解决方案通过返回来处理无效日期None。这会将所有无效日期放在一起:

import datetime

mylist=['ML-M01 Qual Report 07/31/13', 'ML36220010 Complete Qual Testing 07/24/13', 'ML36220045 Final FRB 07/13/13', 'ML9822D2600 Brief to PM 08/5/13']

def extract_date(text):
    try:
        return datetime.datetime.strptime(text.rsplit(None, 1)[-1], '%m/%d/%y')
    except ValueError:
        return None

mylist.sort(key=extract_date)

print mylist

输出:

['ML36220045 Final FRB 07/13/13', 
 'ML36220010 Complete Qual Testing 07/24/13', 
 'ML-M01 Qual Report 07/31/13', 
 'ML9822D2600 Brief to PM 08/5/13']
于 2013-06-18T12:49:51.660 回答