所以我有一个包含姓名,分数和班级的文本文件 e.g。
= ('test', ' in class', '1', ' has got a score of', 1)
我如何对它进行排序(文本文件),以便按分数对其进行数字排序?
答案 0 :(得分:2)
首先,将文件读入列表列表:
with open(filepath, 'r') as file:
list = []
for line in file:
list.append(line[1:-1].split(","))
现在你有这样的事情:
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]]
然后对列表中的列表进行排序:
list.sort(key=lambda x: int(x[4]))
这导致这个排序列表:
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]]
答案 1 :(得分:2)
您可以将sorted()
功能用作
sorted_lines = sorted(lines, key = lambda x : x[4] )
示例强>
>>> lines = [ ('test', ' in class', '1', ' has got a score of', 1),
('test', ' in class', '4', ' has got a score of', 4),
('test', ' in class', '5', ' has got a score of', 5),
('test', ' in class', '3', ' has got a score of', 3),
('test', ' in class', '2', ' has got a score of', 2) ]
>>> sorted_lines = sorted(lines, key = lambda x : x[4] )
>>> soted_lines
('test', ' in class', '1', ' has got a score of', 1)
('test', ' in class', '2', ' has got a score of', 2)
('test', ' in class', '3', ' has got a score of', 3)
('test', ' in class', '4', ' has got a score of', 4)
('test', ' in class', '5', ' has got a score of', 5)