So I have a file:
202010000 Asem ICS104 0 100 100 200
202010000 Asem ICS108 2 75 -1 75
202010001 Khalid ICS202 0 -1 -1 -1
201928690 Hamza ICS104 0 80 -1 80
201928440 Abdullah ICS104 0 100 100 200
202012340 Hassan ICS104 3 60 38 98
201872630 Hadi ICS108 8 90 90 180
201562730 Anwar ICS202 4 75 75 150
201829380 Ali ICS210 3 90 75 165
I need to display all the records in this file in descending order of the total grades (7th column). I asked a very similar question to sort the records alphabetically according to the names (2nd column). The answer for that was this:
studentFile = open(input("Enter file name: "), "r")
lines = studentFile.readlines()
for line in sorted(lines, key=lambda l: l.split()[1]):
print(line)
I tried to do something very similar for the 7th column like this:
studentFile = open(input("Enter file name: "), "r")
lines = studentFile.readlines()
for line in sorted(lines, key=lambda l: l.split()[6], reverse= True):
print(line)
But it doesn't give me the numbers in the correct descending order:
202012340 Hassan ICS104 3 60 38 98
201928690 Hamza ICS104 0 80 -1 80
202010000 Asem ICS108 2 75 -1 75
202010000 Asem ICS104 0 100 100 200
201928440 Abdullah ICS104 0 100 100 200
201872630 Hadi ICS108 8 90 90 180
201829380 Ali ICS210 3 90 75 165
201562730 Anwar ICS202 4 75 75 150
202010001 Khalid ICS202 0 -1 -1 -1
What am I doing wrong?
you need to convert it to int
before sorting, try this:
studentFile = open(input("Enter file name: "), "r")
lines = studentFile.readlines()
for line in sorted(lines, key=lambda l: int(l.split()[6]), reverse= True):
print(line)
output:
202010000 Asem ICS104 0 100 100 200
201928440 Abdullah ICS104 0 100 100 200
201872630 Hadi ICS108 8 90 90 180
201829380 Ali ICS210 3 90 75 165
201562730 Anwar ICS202 4 75 75 150
202012340 Hassan ICS104 3 60 38 98
201928690 Hamza ICS104 0 80 -1 80
202010000 Asem ICS108 2 75 -1 75
202010001 Khalid ICS202 0 -1 -1 -1
edit: @cwittah already said this in the comments, I didn't see it as I was typing out the answer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.