我需要按日期对列表的python列表进行排序 [英] i need to sort a python list of lists by date
问题描述
我需要按日期对列表列表进行排序:
I need to sort a list of lists by date:
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']
从此站点,我获得了以下代码:
from this site, I got this code:
sorted(mylist, key=lambda x: datetime.datetime.strptime(x[2], '%m/%d/%y'))
但是,我收到此错误消息:
however, I get this error message:
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元素对列表进行排序-最旧到最新
need help - need to sort the list by the 3d element - oldest to newest
推荐答案
列表中的每个条目都是字符串,而不是列表,因此 x [2]
是单个字符('-'
作为您的第一个条目).您需要将日期部分 just 拆分为 strptime()
:
Each entry in your list is a string, not a list, so x[2]
is a single character ('-'
for your first entry). You need to split out just the date portion to strptime()
:
sorted(mylist, key=lambda x: datetime.datetime.strptime(x.rsplit(None, 1)[-1], '%m/%d/%y'))
str.rsplit()
在空格上一次分割,以提高效率:
The str.rsplit()
splits on whitespace, once, for efficiency:
>>> '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()
方法:
Note that sorted()
returns a new sorted list, the original list is not affected. If you want to sort mylist
in place, call the list.sort()
method on it:
mylist.sort(key=lambda x: datetime.datetime.strptime(x.rsplit(None, 1)[-1], '%m/%d/%y'))
这篇关于我需要按日期对列表的python列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!