I want to get the scores which the user has to input then order the scores in ascending order however I am struggling to do so. Below is my code so far and it doesn't display the scores in order.Thanks in advance and your help is very much appreciated.
classa = input("what class are you in?")
if classa == "1":
file=open("class 1.csv", "a+")
if classa == "2":
file=open("room2.csv", "a+")
if classa == "3":
file=open("class3.csv", "a+")
score1= int(input("Enter the score 1 results: "))
score2= int(input("Enter the score 2 results: "))
score3= int(input("Enter the score 3 results: "))
newrecord =score1,",",score2,",",score3
file.write(newrecord)
file.write("\n")
file.close()
import csv
import operator
with open('room2.csv','r') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
print (row)
解决方案
You also cannot write a tuple to the file which is what newrecord = score1,",",score2,",",score is creating. You need to make a string from the scores and write that:
newrecord = "{},{},{}\n".formmat(score1,score2,score3)
file.write(newrecord)
To sort existing scores you just need to call sorted on each row, using int as the key to sorted so you values are compared as integers not strings, set reverse=True to order from highest to lowest.
with open('room2.csv','r') as csvfile:
readCSV = csv.reader(csvfile)
for row in readCSV:
srt_row = sorted(row,key=int,reverse=True)
To sum each row and then sort, sum the values after mapping to ints again setting reverse=True to sort from high to low:
with open('room2.csv') as csvfile:
readCSV = csv.reader(csvfile)
srt = sorted((sum(map(int,row)) for row in readCSV), reverse=True)
If you want to write to a file:
with open('room2.csv','r') as csvfile, open("out.csv","w") as out:
readCSV = csv.reader(csvfile)
for scre in sorted((sum(map(int, row)) for row in readCSV), reverse=True):
out.write(str(scre))