Reputation: 579
I have saved various scores to a text file using Python. Here is how the text file is structured (the name of the text file is class_a.txt):
Ben,10
Harry,4
Joe,6
Adam,7
Anthony,10
I have managed to sort the scores alphabetically, here is the code for that:
def alpha():
if class_name == "a":
with open("class_a.txt") as f:
lines = f.readlines()
lines = sorted(lines)
for line in lines:
name = line[:line.find(",")]
marks = line[line.find(",")+1:].split(",")
marks = sorted(marks)
print(name + "'s Score = " + marks[-1])
This code outputs the scores like this:
Adam's Score = 7
Anthony's Score = 10
Ben's Score = 10
Harry's Score = 4
Joe's Score = 6
However I would also like to add an option to sort the scores from highest to lowest.
For example when Python outputs the data from the text file, it will look like this:
Anthony's Score = 10
Ben's Score = 10
Adam's Score = 7
Joe's Score = 6
Harry's Score = 4
Upvotes: 0
Views: 1872
Reputation: 22282
You just need:
def alpha():
if class_name == "a":
with open("class_a.txt") as f:
lines = sorted([i.strip().split(',') for i in f],
key=lambda x: (-int(x[1]), x[0]),
reverse=True)
for name, score in lines:
print(name + "'s Score = " + score)
Demo:
Anthony's Score = 10
Ben's Score = 10
Adam's Score = 7
Joe's Score = 6
Harry's Score = 4
Upvotes: 2
Reputation: 10460
Here's a more Pythonic way of achieving what you're after:
import csv
with open("class_a.txt") as file:
csv_reader = csv.reader(file)
sorted_list = sorted(csv_reader, key=lambda row: int(row[1]), reverse=True)
for name, score in sorted_list:
print("{0}'s Score = {1}".format(name, score))
Output:
Ben's Score = 10
Anthony's Score = 10
Adam's Score = 7
Joe's Score = 6
Harry's Score = 4
By using the csv
module, you are able to generate an array for each row in the file and use sorted
to sort the list generated based on a specific column.
Upvotes: 3