2015-05-04 160 views
0

我目前正在開發一個代碼,根據用戶的選擇對來自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

你應該和你正在使用的語言標記這個(蟒蛇,我認爲) – arvi1000

+0

@ arvi1000啊我的壞,感謝 – chiefkeef12

回答

0

因爲你想要做的是基於數字排序,你應該有key函數轉換你想要整數的值。這裏有一個例子讓你開始:

values = [('Alice', '80'), ('Bob', '5'), ('Chuck', '80')] 
sorted(values, key = lambda row: (-int(row[1]), row[0])) 
+0

感謝您的幫助,所以不是這個,如果sorttype == 1:sorting = sorted(read,key = operator.itemgetter(0,6))我應該使用您提供的內容。或者你是否建議我在排序之前將這些值更改爲整數? – chiefkeef12

+0

第一種排序的方式正確嗎?我建議改變第二和第三種排序方式,根據整數值而不是字符串進行排序。 – Julian

+0

是的。而且我看到了,我不熟悉lambda:/但我會試着看看會發生什麼。謝謝 – chiefkeef12