Python : Sort file by arbitrary column, 其中列包含时间值

标签 python sorting

我有一个人的 .txt 文件,每个人旁边有两次。这是 .txt 文件

 Xantippe 09:00 11:00
 Erica 10:00 12:06
 Marcia 09:30 11:45
 Elizabeth 10:15 12:10
 Angela 11:30 13:45
 Freda 12:00 14:20
 Maria 12:30 14:10

我需要读取文件,然后获取每一行,读取它,然后第二次对整个列表进行排序。请记住,在文件中,数字是字符串对象。所以基本上最早的时间即 11:00 应该与他们之前的时间和姓名一起位于列表的顶部。例如。 Xantippe 09:00 11:00 然后在另一行下一行等

到目前为止我已经做了:

from Practise1 import timeCalc
with open('LadiesRace.txt', 'r') as f:
  readf = f.read();
  timeX = timeCalc()
  lis = readf.split('\n')
  with open('sortByFinishTime.txt','w') as w:
    def compare(x,y):
      if x[1] > y[1]:
        return 1
      if x[1] < y[1]:
        return -1
      return 0
    #lis.sort()
    for l in lis:
      #line = l.strip()
      slist = l.split(' ')
      print slist[2]

问题是我不能使用字典,只能使用列表。我已设法按名称升序对列表进行排序,但我该如何与上次排序?

最佳答案

首先,您需要将数据转换为可用格式...所以让我们将其加载到内存中的列表中 - 重要的是要注意 dict 本身没有顺序,因此我们想要使用列表。

with open('myfile.txt') as fin:
    lines = [line.split() for line in fin]

这将删除任何尾随的换行符并用空格字符将其分开......所以我们最终得到:

[['Xantippe', '09:00', '11:00'], ['Erica', '10:00', '12:06'], ['Marcia', '09:30', '11:45'], ['Elizabeth', '10:15', '12:10'], ['Angela', '11:30', '13:45'], ['Freda', '12:00', '14:20'], ['Maria', '12:30', '14:10']]

然后,我们可以使用 list.sort 方法 - itemgetter 是获取序列第 n 个元素的便捷方法, 所以我们有名称、开始、结束,其中结束是第二个索引(基于零是第一个,这将是名称)

from operator import itemgetter
lines.sort(key=itemgetter(2))

我们最终得到:

[['Xantippe', '09:00', '11:00'], ['Marcia', '09:30', '11:45'], ['Erica', '10:00', '12:06'], ['Elizabeth', '10:15', '12:10'], ['Angela', '11:30', '13:45'], ['Maria', '12:30', '14:10'], ['Freda', '12:00', '14:20']]

然后写回去:

with open('output.txt', 'w') as fout:
    for el in lines:
        fout.write('{0}\n'.format(' '.join(el)))

关于Python : Sort file by arbitrary column, 其中列包含时间值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13528800/

相关文章:

python - djangorest-framework单例ViewSet

Python:多级嵌套列表

java - 为什么我的堆排序比 Java 和 C++ 的排序函数快?

c++ - 为什么函数比较器不能像在排序中那样在优先级队列中工作?

python - 如何从 CMD 运行 Pip 命令

python - Django + 后台任务如何初始化

c# - C# 中的字符串 "Sort Template"

javascript - 基于嵌套数组中匹配值的angularjs过滤器

python - win.blit()后台pygame时出现滞后

jquery - 使用 jQuery DataTables 恢复原始排序顺序