簡體   English   中英

氣泡排序算法| 'str'對象不支持項目分配-Python

[英]Bubble sort algorithm | 'str' object does not support item assignment - Python

簡介:我挑戰自己編寫一個程序,按照教科書中的要求,測試我的理解並證明自己在“泡沫排序”中的熟練程度。 問題要求編寫一個程序,該程序“允許用戶在String數組中輸入20個名稱。按升序(字母順序)對數組進行排序並顯示其內容。” 我最初的代碼起作用了,但是我不滿意,后來又嘗試更改一個未成功的代碼,我被一個可行的解決方案所困擾。

問題:我最初用一個循環編寫了friendInput函數,該函數迭代20次( for listInput in range(20): ),以允許20個單獨的輸入,分別對應於用戶輸入的20個值。 盡管這樣做有效,但我認為從用戶的角度來看非常繁瑣,尤其是在范圍為20的情況下,必須繼續鍵入,按回車鍵,然后重復輸入20個值。

原始代碼:

def friendInput():                                               
    friendList  = []                                             
    for listInput in range(20):                                  
        friendList.append(input("Please enter a friends name: "))      
    print("You added these to the list: "+' | '.join(friendList))
    return friendList   

嘗試的代碼重寫:

def friendInput():
    friendList = []
    separator = ","
    friendList = input("Please enter friend's names, separated with commas: ")
    print("You added these to the list:",friendList.split(separator))
    return friendList

我做了一些研究,並學到了很多東西,包括.split()函數,並試圖實現它,但未成功。 氣泡排序算法:

def bubbleSort(friendList):
    for friends in range (0, len(friendList) - 1):
        for x in range (0, len(friendList) - 1 - friends):
            if friendList[x] > friendList[x+1]:
                friendList[x], friendList[x+1] = friendList[x+1],  friendList[x]
    return friendList

錯誤消息:在我看來,一切似乎合乎邏輯,直到調試器向后TypeError: 'str'對象不支持項目分配。 TypeError:繼續引用我的bubbleSort函數的一部分friendList[x], friendList[x+1] = friendList[x+1], friendList[x]

在需要幫助的地方:我想錯誤實際上是在說我正在嘗試訪問和更改字符串,這顯然是不允許的,因為它不是一成不變的。 我正在努力尋找看起來清晰,簡潔且不會給用戶帶來負擔的代碼更改。

有人可以提出建議來糾正此錯誤嗎?

重新閱讀這些行:

friendList = input("Please enter friend's names, separated with commas: ")
print("You added these to the list:",friendList.split(separator))
return friendList

您正在創建一個字符串friendList = input ...,然后返回該字符串( return friendList )。 您打算創建一個列表,然后返回該列表。

嘗試以下方法:

friendList = input("Please enter friend's names, separated with commas: ")
friendList = friendList.split(separator)
print("You added these to the list:",friendList)
return friendList

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM