2017-01-02 77 views
0

有一個我希望按照字母順序排序電子郵件的bubblesort程序。但是,當我運行帶有列表的程序時,我想對其進行排序,得到錯誤TypeError:'tuple'對象不支持項目分配。 下面是代碼:列表未被排序BubbleSort

def BubbleSort(logindata): 
    NoSwaps = 1 
    N = len(logindata) 
    while NoSwaps == 1: 
     Count = 1 
     NoSwaps = 0 
     for Count in range(N-1): 
      if logindata[Count] > logindata[Count+1]: 
       temp = logindata[Count] 
       logindata[Count] = logindata[Count+1] 
       logindata[Count+1]=temp 
       NoSwaps=1 
    return logindata 

if __name__ == "__main__": 
    logindata=["[email protected]","Password1"],["Harry","Password2"],["Jake","Password3"] 
    BubbleSort(logindata) 
    print(logindata) 

程序排序列表,但不「密碼」。我將如何讓代碼運行併成功地對其進行排序。

+1

你是不是捕捉從'BubbleSort'函數的返回值。捕獲返回值並打印出來。 – karthikr

回答

2

隨着假設你的冒泡排序算法正常工作,你的問題是你不能在tuple分配項目,儘量logindata[count] = logindata[count+1]的時候,你可以改變logindatalist然後返回logindatatuple,並且你也應該捕獲返回logindata然後打印出來,整個代碼看起來是這樣的:

def BubbleSort(logindata): 
    NoSwaps = 1 
    N = len(logindata) 
    logindata = list(logindata) 
    while NoSwaps == 1: 
     Count = 1 
     NoSwaps = 0 
     for Count in range(N-1): 
      if logindata[Count] > logindata[Count+1]: 
       temp = logindata[Count] 
       logindata[Count] = logindata[Count+1] 
       logindata[Count+1]=temp 
       NoSwaps=1 
    return tuple(logindata) 

if __name__ == "__main__": 
    logindata=["[email protected]","Password1"],["Harry","Password2"],["Jake","Password3"] 
    logindata = BubbleSort(logindata) 
    print(logindata) 
    #(['Harry', 'Password2'], ['Jake', 'Password3'], ['[email protected]', 'Password1']) 
0

此代碼將運行並對列表進行排序。不過,我不知道這是否是你想要的方式。

def BubbleSort(logindata): 
    NoSwaps = 1 
    N = len(logindata) 

    while NoSwaps == 1: 
     Count = 1 
     NoSwaps = 0 

     for Count in range(N-1): 
      if logindata[Count][0] > logindata[Count+1][0]: 
       temp = logindata[Count][0] 
       logindata[Count][0] = logindata[Count+1][0] 
       logindata[Count+1][0] =temp 
       NoSwaps=1 
       temp = logindata[Count][1] 
       logindata[Count][1] = logindata[Count+1][1] 
       logindata[Count+1][1] =temp 
    return logindata 

if __name__ == "__main__": 
    logindata=["Adam","Password1"],["Harry","Password2"],["Cake","Password3"] 
    BubbleSort(logindata) 
    print(logindata)