2017-07-18 157 views
0

給定一個隨機序列的人員列表,我需要編寫一個函數,對人員進行排序並返回一個列表,以便老年人在列表的前面。如果我的輸入是[("M" , 23), ("F" , 19), ("M" , 30)],我的函數應該返回[("M", 30), ("M", 23), ("F", 19)]。我的功能如下:排序列表而不使用.sort或排序函數(Python 3.6)

def sort_age(lst): 
    new_lst=[] 
    while lst: 
     max_age = lst[0][1] 
     oldest = lst[0] 
     counter = len(lst)-1 
     while counter > 0: 
      if lst[counter][1] > max_age: 
       max_age = lst[counter][1] 
       oldest = lst[counter] 
       counter-=1 
      lst.remove(oldest) 
      new_lst.append(oldest) 
    return new_lst 

Python IDLE拋出ValueError: list.remove(x): x not in list。我的代碼中的錯誤在哪裏,我該如何糾正它?

+0

使用buitin'sorted'功能:'排序(LST,鍵=拉姆達X:X [1],反向= TRUE)'。另外,while'lst'和'counter = len(lst)-1'的組合同時從'lst'中移除元素是非常成問題的。 – Abdou

回答

0

我會使用內置sorted避免重蹈覆轍:

lst = [("M" , 23), ("F" , 19), ("M" , 30)] 
print(sorted(lst, key=lambda x: x[1], reverse=True)) 

# [('M', 30), ('M', 23), ('F', 19)] 

但是,如果你希望寫一個排序函數,那麼你應該重寫功能類似於以下內容:

def sort_by_age(local_lst): 
    local_lst = local_lst[:] 
    output = [] 
    while True: 
     if len(local_lst) == 0: 
      break 
     oldest = local_lst[0] 
     max_age = oldest[1] 
     for tpl in local_lst[:]: 
      if tpl[1] > max_age: 
       max_age = tpl[1] 
       oldest = tpl 
     output.append(oldest) 
     local_lst.remove(oldest) 
    return output 

lst = [("M" , 23), ("F" , 19), ("M" , 30)] 
print(sort_by_age(lst)) 

# [('M', 30), ('M', 23), ('F', 19)] 

有一點可以幫助您找出爲什麼ValueError異常正在拋出主要是.append.remove操作正在第二個while loop內完成。即使在第一個while loop的第二次迭代之前,這本質上也會清空清單。由於第二個while loop用於確定當前的max_age是什麼,因此最好將.append.remove操作移到循環之外,以便刪除實際的最大元組。

以下是最接近你開始使用什麼:

def sort_age(lst): 
    local_list = lst[:] 
    new_lst=[] 
    while len(local_list) != 0: 
     max_age = local_list[0][1] 
     oldest = local_list[0] 
     counter = len(local_list)-1 
     while counter >= 0: 
      if local_list[counter][1] > max_age: 
       max_age = local_list[counter][1] 
       oldest = local_list[counter] 
      counter -= 1 
     local_list.remove(oldest) 
     new_lst.append(oldest) 
    return new_lst 

請注意,我複製原始列表以確保該函數返回一個新的列表,而不是僅僅排空原始列表。

我希望這有助於

+0

感謝您提供詳細和翔實的回覆,Abdou。這有助於我更好地理解如何編寫適合我的問題的排序功能。真的很感激它。 –

0
 lst.remove(oldest) 
     new_lst.append(oldest) 

縮進一次太多。

+0

這不提供問題的答案。要批評或要求作者澄清,請在其帖子下方留言。 - [來自評論](/ review/low-quality-posts/16749854) – ppperry

+0

他詢問了代碼中的錯誤以及如何糾正錯誤。錯誤是這兩行縮進錯誤,更正是縮小一行。代碼沒有其他錯誤。沒有需要澄清。看起來像複製和粘貼錯誤。 –

+0

在這種情況下,您應該將問題標記爲「此問題是由於無法再現的問題或簡單的印刷錯誤導致的。雖然類似的問題可能在此處討論,但這一問題以不太可能幫助未來的讀者,這通常可以通過識別並密切檢查在發佈之前重現問題所需的最短程序來避免。「 – ppperry