按d对行排序

2024-05-29 04:20:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

所以我想按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

我该怎么做

谢谢你花时间回答


Tags: 文件thetxtprojectnew排序moviewatch
1条回答
网友
1楼 · 发布于 2024-05-29 04:20:28

使用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])

这假设ever行在位置2处有creationDate前缀。然而,正如注释所指出的,是否有些行有x前缀而有些行没有?如果没有,是否有字符(例如\s\t

相关问题 更多 >

    热门问题