python写csv文件按升序排列_如何在从python做的csv文件中按升序排序数字

1586010002-jmsa.png

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值