Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

How to sort numbers in ascending order in a csv file made from python

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("
")

file.close()


import csv

import operator

with open('room2.csv','r') as csvfile:

    readCSV = csv.reader(csvfile, delimiter=',')

    for row in readCSV:

        print (row)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = "{},{},{}
".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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...