冒泡排序算法 | 'str' 对象不支持项目分配 - Python

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

简介: 我挑战自己编写了一个程序,正如教科书中所要求的那样,以测试我对 'bubble sort' 的理解和熟练程度。该问题要求编写一个程序 "allows the user to enter 20 names into a String array. Sort the array in ascending (alphabetical) order and display its contents." 我的初始代码有效,但我并不满意,后来尝试更改代码失败,我很难找到一个可行的解决方案。

问题: 我最初用 for 循环编写 friendInput 函数,迭代 20 次 (for listInput in range(20):),允许 20 个人输入,分别为用户输入的 20 个值。虽然这行得通,但我认为从用户的角度来看非常乏味,尤其是范围为 20,必须继续键入,点击 return,然后重复 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 创建该字符串 (return friendList)。您打算创建一个列表,然后 return 该列表。

试试这个:

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