我想从文本文件中对内容进行排序。我已经按字母顺序(名称)对它们进行了排序。我得到的问题是,当我尝试按升序或降序对分数进行排序时,程序不会将10识别为10而是将其识别为1.我已附加了我的代码和文本文件。
Python 3.4 代码:
import csv
import operator
quizGrades= open('Quiz-1.txt' , 'r')
def menu():
print('To Check The scores by ALPHABETICLE Order [1]')
print('To Check The Scores In ASCENDING Order [2]')
print('To check the AVERAGE Scores of Each Student [3]')
choice=int(input(':'))
if choice==1:
alpha()
elif choice==2:
ascend()
def alpha():
quizGrades = open('Quiz-1.txt' , 'r')
grades = csv.reader(quizGrades, delimiter =',')
sortedGrades = sorted(grades, reverse= False, key=operator.itemgetter(1))
for eachline in sortedGrades:
print()
print (eachline)
quizGrades.close()
def ascend():
quizGrades = open('Quiz-1.txt' , 'r')
grades = csv.reader(quizGrades, delimiter =',')
sortedGrades = sorted(grades, reverse= False, key=operator.itemgetter(4))
for eachline in sortedGrades:
print()
print (eachline)
quizGrades.close()
menu()
文本文件
Name:,Aum Patel,Class:1,Score:,10,/10
Name:,Lolly Pop,Class:1,Score:,9,/10
Name:,Kimjon Un,Class:1,Score:,5,/10
Name:,Gurpreet Perv,Class:1,Score:,7,/10
Name:,Aum Patel,Class:1,Score:,8,/10
Name:,Amanjeet Singh,Class:1,Score:,2,/10
Name:,Kimjon Un,Class:1,Score:,1,/10
Name:,Aum Patel,Class:1,Score:,10,/10
Name:,Chong Singh,Class:1,Score:,1,/10
Name:,Amanjeet Singh,Class:1,Score:,7,/10
Name:,Akky Chandrakumar,Class:1,Score:,8,/10
答案 0 :(得分:1)
您需要将从txt文件读取的字符串转换为整数
grades = [int(grade) for grade in grades]
如果你比较字符串,结果将如下
numString = ["1","5000","3","6","30","4","2","200"]
print(sorted(numString))
['1', '2', '200', '3', '30', '4', '5000', '6']
答案 1 :(得分:1)
您将数字排序为字符串,而不是数字。您需要更改ascend()
功能,如下所示:
def ascend():
quizGrades = open('Quiz-1.txt' , 'r')
grades = csv.reader(quizGrades, delimiter =',')
sortedGrades = sorted(grades, reverse= False, key=lambda x: int(x[4]))
for eachline in sortedGrades:
print()
print (eachline)
quizGrades.close()
key=lambda x: int(x[4])
会将数字转换为排序的整数,而不会更改字符串的输出。
我还建议CSV文件的更常见格式为:
"Name","Class","Score","Total Points"
"Aum Patel",1,10,10
...
第一行是标题行,后续行只包含值,因此不需要从文本文件同一行的标签中解析出值。使用此格式,并使用quoting=csv.QUOTE_NONNUMERIC
csv.reader()
行,您的原始排序可行:
import csv
import operator
with open('Quiz-1.txt', 'r') as f:
grades = csv.reader(f, delimiter=",", quoting=csv.QUOTE_NONNUMERIC) # Treat any unquoted values as floats.
next(grades) # Skip the header row.
sorted_grades = sorted(grades, reverse=False, key=operator.itemgetter(2)) # Just changed column.
for row in sorted_grades:
print(row)