python初学者:'print mystr.split(',')出了什么问题.sort(reverse = True)'

pro*_*joy 2 python

我尝试从字符串中排序一个数字序列:

在python解释器中:

    >>> mystr = '1,2,3,4,5'
    >>> a = mystr.split(',')
    >>> a
    ['1', '2', '3', '4', '5']
    >>> a.sort(reverse=True)
    >>> a
    ['5', '4', '3', '2', '1']
Run Code Online (Sandbox Code Playgroud)

但是当我想缩短代码时,会出现问题:

    >>> mystr
    '1,2,3,4,5'
    >>> print mystr.split(',').sort(reverse=True)
    None
Run Code Online (Sandbox Code Playgroud)

为什么会这样?希望得到你的帮助!

nu1*_*73R 6

sort()不返回一个新的列表,而是排序上的函数被调用列表

更精确地, sort()是否对列表进行就地排序

>>> a = mystr.split(',')
>>> a.sort(reverse=True) # Nothing is returned at this line
>>> a # But the list is sorted
['5', '4', '3', '2', '1']
Run Code Online (Sandbox Code Playgroud)

如果要返回排序列表,请使用 sorted()函数

>>> sorted(mystr.split(','), reverse=True)
['5', '4', '3', '2', '1']
Run Code Online (Sandbox Code Playgroud)

边注:sortVS sorted可能导致详细讨论的就地排序算法的效率.由于该sort函数不会创建新列表,因此它的内存效率会比sorted.也sort可以处理更大的列表.