“元组”对象没有属性“排序……”排序功能在 jupyter notebook 中不起作用?

新手上路,请多包涵
new_list=("a","g","x","e","s","s")     #created a list
a=new_list.sort()   #try to sort it

错误是:

 AttributeError Traceback (most recent call last)
<ipython-input-3-6eb33c65fab6> in <module>()
----> 1 a=new_list.sort()
AttributeError: 'tuple' object has no attribute 'sort'

我收到此属性错误。我重新启动了我的内核,并在 sublime-text-CMD 上尝试了它。我仍然遇到同样的错误

原文由 keshav N 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 581
2 个回答

如果您在这里看到 “元组和序列” ,您可以看到您的数据结构是一个元组。

您可以在此处 “更多列表” 中看到 sort() 是仅适用于数组的函数。

您可以使用 sorted() 对数组或元组进行排序

new_list=("a","g","x","e","s","s")
a=sorted(new_list) # ['a', 'e', 'g', 's', 's', 'x']

原文由 Hearner 发布,翻译遵循 CC BY-SA 4.0 许可协议

new_list 被定义为 tuple 。通过将其括在方括号中使其成为 list

 new_list=["a","g","x","e","s","s"]
new_list.sort()
print (new_list)
# ['a', 'e', 'g', 's', 's', 'x']

原文由 Sunitha 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题