如何对数值最高到最低的文本文件进行排序? [英] How do i sort a text file numerically highest to lowest?
本文介绍了如何对数值最高到最低的文本文件进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个文本文件,其中包含名称,分数和类 例如
So i have a text file containing names,scores and class in there e.g.
= ('test', ' in class', '1', ' has got a score of', 1)
我如何对它(文本文件)进行排序,以便按分数对它进行数字排序?
How can i sort it (text file) so that it sorts it numerically by the score?
推荐答案
首先,将文件读入列表列表:
First, read the file into a list of lists:
with open(filepath, 'r') as file:
list = []
for line in file:
list.append(line[1:-1].split(","))
现在您有类似这样的内容:
Now you have something like this:
list == [['test', ' in class', '1', ' has got a score of', 3],
['test', ' in class', '1', ' has got a score of', 5],
['test', ' in class', '1', ' has got a score of', 1],
['test', ' in class', '1', ' has got a score of', 2]]
然后对列表内的列表进行排序:
Then sort lists inside the list:
list.sort(key=lambda x: int(x[4]))
这将产生以下排序列表:
This results in this sorted list:
list = [['test', ' in class', '1', ' has got a score of', 1],
['test', ' in class', '1', ' has got a score of', 2],
['test', ' in class', '1', ' has got a score of', 3],
['test', ' in class', '1', ' has got a score of', 5]]
这篇关于如何对数值最高到最低的文本文件进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文