按日期排序

时间:2018-04-17 17:38:49

标签: python python-3.x sorting datetime

所以我有一个包含一些行的.txt文件...... 每行具有以下格式:x (A-Z) creationDate completionDate Task +project @context(TODO列表项目)

所以我想通过他们的creationDate(以及第二种情况的completionDate)对这些行进行排序,并将它们写在.txt文件中。

示例:

  (D) 2018-03-02 2018-04-04 watch the new tomb raider +movie @tombraider
  (A) 2017-03-02 2017-03-10 say goodbye to your best friend!! +friendship @meetfriend

x (C) 2016-07-02 2016-08-05 finish gta vice city +gaming @playstation2
排序后

x (C) 2016-07-02 2016-08-05 finish gta vice city +gaming @playstation2
  (A) 2017-03-02 2017-03-10 say goodbye to your best friend!! +friendship @meetfriend
  (D) 2018-03-02 2018-04-04 watch the new tomb raider +movie @tombraider

我该怎么做?

感谢您花时间回答。

1 个答案:

答案 0 :(得分:0)

使用sorted()lambda

with open(myfile, 'r') as f:
    lines = [line.strip().split() for line in f]

sorted_lines = sorted(lines, key = lambda x: x[2])

这假设任何行都会在位置2处有creationDate。但是,正如评论已经指出的那样,某些行有一个x前缀而有些行不是吗?如果不是,那里是否有字符(例如\s\t)?

相关问题