2014-12-03 31 views
0

我之前已經問過類似的問題,所以我很抱歉,但是我讀回任務並誤解了最初的需求。排序字典鍵內的列表 - 從列表中獲得最高分3

因此,基於我在這裏獲得的反饋,這是我使用的代碼:

def task3(): 
    classList = {} 
    classSearch = input("Which class would you like to interrogate? ") 
    try: 
     with open("answers " + classSearch + ".txt", 'rb') as handle: 
      classList = pickle.loads(handle.read()) 
    except IOError as error: 
     print ("Sorry, this file does not exist") 

    sortOption = int(input("Would you like sort the students in alphabetical order? Enter 1\n Would you like to sort the students by highest score? Enter 2 \nWould you like to sort students by their average score?Enter 3\n")) 
    if sortOption == 1: 
     x = sorted(classList.items()) 
     for key, value in x: 
      value.sort() 
      value.reverse() 
     print (x) 

所以我真正需要做的是輸出每個學生的最高分,是按字母順序排序名稱。在classList字典裏面是學生名字,然後是包含他們在測驗中收到的最後3個分數的列表。對於多名學生來說這顯然是重複的。任何幫助將大規模讚賞。

+0

標準字典是無序的。這意味着你無法對其進行分類。我想你需要一個有序的詞典。 https://docs.python.org/2/library/collections.html#collections.OrderedDict – 2014-12-03 10:56:45

+0

謝謝,我自己最後通過打印索引位置來修復它0 – RH84 2014-12-03 12:27:23

回答

0

像這樣的事情應該工作,假設輸入是完全無序:

for name,highscore in [(student,max(classList[student])) for student in sorted(classList.keys())]: 
    print name,highscore 

ETA

按照要求,提供了一個解釋。

classList是一個dict,每個成員由一個鍵(學生的名字)和一個值(該學生的分數列表)組成。

我建議的代碼遍歷預先排序的列表,理解包含學生姓名和該學生最高分數的元組,並依次打印每個元組。

列表理解完成這裏的所有工作。

classList.keys()產生一個包含學生姓名的列表。在這種情況下,內置的sorted函數返回相同的按字母順序排序。

列表理解就像一個for循環,遍歷鍵列表並構建一個元組列表。

你也可以說

sortedNames = sorted(classList.keys()) 
for student in sortedNames: 
    high_score = max(classList[student]) 
    print student, high_score 
+0

嗨,我處於與OP類似的情況。此代碼爲我工作。你能解釋一下嗎,因爲我不明白嗎? – Kaiylar 2016-05-21 10:19:03

+0

另外,哪些是變量?學生是一個變量嗎?如果不是,那是什麼? – Kaiylar 2016-05-21 11:20:15

+0

@Kaiylar,變量有點不恰當,我認爲它是Python的標籤? – selllikesybok 2016-05-21 12:26:51

相關問題