gpt4 book ai didi

python - 属性错误 : 'str' object has no attribute 'sort'

转载 作者:太空宇宙 更新时间:2023-11-03 13:19:41 26 4
gpt4 key购买 nike

任务读...

Write a program that takes a list of student names and sorts them to create a class roll. The list of names will be given on a one line separated by a single space.

所以我有我的代码。

items=input("Students: ")
items.sort(lambda x, y: cmp(x.lower(),y.lower()))
print(items)

为什么我会得到这个,“AttributeError:‘str’对象没有属性‘sort’”错误

进阶加油

罗尼

最佳答案

input() 返回一个字符串。如果您希望 items 成为一个列表,您可以执行 item.split():

假设 itemsJohn Mary Bill

然后你可以这样做:

items = items.split()

然后执行 items.sort(),因为 items 将是一个列表对象,而不是字符串。

关于python - 属性错误 : 'str' object has no attribute 'sort' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18568338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com