sort() and reverse() functions do not work

后端 未结 4 585
轻奢々
轻奢々 2020-11-22 12:42

I was trying to test how the lists in python works according to a tutorial I was reading. When I tried to use list.sort() or list.reverse(), the in

相关标签:
4条回答
  • 2020-11-22 12:52

    For reference, you can see the documentation here specifically says:

    The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.

    Don't be afraid to read the manual!

    0 讨论(0)
  • 2020-11-22 13:02

    This methods operate in place.

    This code works (python 3.x)

    a = [66.25, 333, 333, 1, 1234.5]
    a.sort()
    print(a)
    a.reverse()
    print(a)
    
    >>> 
    [1, 66.25, 333, 333, 1234.5]
    [1234.5, 333, 333, 66.25, 1]
    
    0 讨论(0)
  • 2020-11-22 13:08

    .sort() and .reverse() change the list in place and return None See the mutable sequence documentation:

    The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.

    Do this instead:

    a.sort()
    print(a)
    a.reverse()
    print(a)
    

    or use the sorted() and reversed() functions.

    print(sorted(a))               # just sorted
    print(list(reversed(a)))       # just reversed
    print(a[::-1])                 # reversing by using a negative slice step
    print(sorted(a, reverse=True)) # sorted *and* reversed
    

    These methods return a new list and leave the original input list untouched.

    Demo, in-place sorting and reversing:

    >>> a = [66.25, 333, 333, 1, 1234.5]
    >>> a.sort()
    >>> print(a)
    [1, 66.25, 333, 333, 1234.5]
    >>> a.reverse()
    >>> print(a)
    [1234.5, 333, 333, 66.25, 1]
    

    And creating new sorted and reversed lists:

    >>> a = [66.25, 333, 333, 1, 1234.5]
    >>> print(sorted(a))
    [1, 66.25, 333, 333, 1234.5]
    >>> print(list(reversed(a)))
    [1234.5, 1, 333, 333, 66.25]
    >>> print(a[::-1])
    [1234.5, 1, 333, 333, 66.25]
    >>> print(sorted(a, reverse=True))
    [1234.5, 333, 333, 66.25, 1]
    >>> a  # input list is untouched
    [66.25, 333, 333, 1, 1234.5]
    
    0 讨论(0)
  • 2020-11-22 13:11

    A simple ascending sort is very easy, call the sorted() function. It returns a new sorted list:

    >>> sorted([66.25, 333, 333, 1, 1234.5])
    [1, 66.25, 333, 333, 1234.5]
    

    sorted() accept a reverse parameter with a boolean value.

    >>> sorted([66.25, 333, 333, 1, 1234.5], reverse=True)
    [1234.5, 333, 333, 66.25, 1]
    
    0 讨论(0)
提交回复
热议问题