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 nume
Solution 1:
You can use the sorted()
function as
sorted_lines = sorted(lines, key = lambda x : x[4] )
Example
>>> 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)
Solution 2:
First, read the file into a list of lists:
withopen(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]]
Post a Comment for "How Do I Sort A Text File Numerically Highest To Lowest?"