'tuple' object has no attribute 'sort.......排序功能在 jupyter notebook 中不起作用?

'tuple' object has no attribute 'sort.......Sort function not working in 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 上尝试了它。我仍然得到同样的错误

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

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

元组是一系列不可变的 Python 对象,这意味着您无法更改它们的值。也许您打算使用 sorted 而不是 sort ?

new_list=("a","g","x","e","s","s")

a = sorted(new_list)

如果你看到这里 "Tuples and Sequences" 你可以看到你的数据结构是一个元组。

你可以在这里"More on Lists"看到sort()是一个仅适用于数组的函数。

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

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