我目前正在开发一个代码,根据用户的选择对csv文件中的数据进行排序。
目前我遇到麻烦,因为我对最高分的分类并没有真正起作用。它将10识别为010,因此推断它比09等的其他数字少。有什么方法可以解决这个问题吗?
http://postimg.org/image/onfbhpaxn/这是我目前得到的结果
这是我用来锻炼最高分的代码。
high = max(int(x) for x in row[2:4]) # finds the highest score from the row 2:4
high = str("0") + str(high) # adds a 0 in front of the high score so that it could be used for sorting
row.insert( 6, high) #insert the high value on row 6
write.writerows([row[:7]])
这是我用来排序的代码。
if choice == 2: #if choice is 2
form = input("Enter a class to sort it's Data: ")
filename = 'class{}.csv'.format(form)
print("• Enter 1 to sort by student's highest score in alphabetical order. ")
print("• Enter 2 to sort by student's highest score (highest to lowest)")
print("• Enter 3 to sort by Student's average score (highest to lowest)")
sorttype = int(input("Choose a option from above to sort: ")) # ask the teacher to choose an option for the sorting from above
print(" ") #prints out nothing (space ) so that the sorted data is layed out in a neater way
with open (filename,'r', newline='') as keerthan: #open the file to read using csv writer
read = csv.reader(keerthan,delimiter=',') #creates a function to read lines in the sort file
if sorttype == 1: sorting = sorted(read, key=operator.itemgetter(0,6)) # if the student choses 1 ; sort it in alphabetical order
elif sorttype == 2:sorting = sorted(read, key=operator.itemgetter(6,0), reverse = True) #if choice 2 , sort it is lowest to highest and then reverse.
elif sorttype == 3:sorting = sorted(read, key=operator.itemgetter(5,0), reverse = True) # if choice 3 , sort by average score ; lowest to highest and then reverse.
for row in sorting: # for every row in the file
if row[0].startswith("Name"):None #if the first column is "name" (like the header): skip it
else: #else (otherwise)
if sorttype == 3: print(row[0] + ' ' + row[1] + ': ' + row[5]) #otherwise print FirstName, SecondName and average score
else:print(row[0] + ' ' + row[1] + ': ' + row[6])
谢谢。
答案 0 :(得分:0)
由于你想要做的是根据数字排序,你应该让key
函数转换你想要整数的值。这是一个让你入门的例子:
values = [('Alice', '80'), ('Bob', '5'), ('Chuck', '80')]
sorted(values, key = lambda row: (-int(row[1]), row[0]))