首先,您需要将数据转换为可用的格式...所以让我们将其加载到内存中的列表中 - 重要的是要注意这一点dict
s 本身没有顺序,所以我们想使用列表。
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']]
然后,我们可以使用.sort
的方法list
- itemgetter
是获取序列中第 n 个元素的便捷方法,因此我们有 name、start、end,其中 end 是第二个索引(基于零作为第一个元素,这将是名称)
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)))