search

Home  >  Q&A  >  body text

flask - python让列表倒序输出

想请问下python中用下面的语法就可以让一个list倒序

list = [1, 2, 3, 4, 5, 6]
print list[::-1]

想请问下其中是什么道理吗,还是就是一种特定用法记住就好了

怪我咯怪我咯2813 days ago953

reply all(4)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 11:46:13

    The slice of list has three parameters: starting point, end point, step size

    list[::-1] is equivalent to the starting point being the last one, the end point being the first one, and then decreasing one at a time

    See more tests below

    >>> a = [0,1,2,3,4,5,6,7,8,9]
    >>> a
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> a.reverse()
    >>> a
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    >>> a.reverse()
    >>> a
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> a[:]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> a[::]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> a[5::-1]
    [5, 4, 3, 2, 1, 0]
    >>> a[:5:-1]
    [9, 8, 7, 6]
    >>> a[5:1:-1]
    [5, 4, 3, 2]
    

    reply
    0
  • 阿神

    阿神2017-04-17 11:46:13

    I am here to post the document——

    1. The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 which end depends on the sign of k). Note , k cannot be zero. If k is None, it is treated like 1.

    PS: Once again encountered the problem that Markdown does not support starting a list other than 1...

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 11:46:13

    a = [0,1,2,3,4,5,6,7,8,9]
    b = a[i:j] means copying a[i] to a[j-1] to generate a new list object
    b = a[1:3] Then, the content of b is [1,2]
    When i is defaulted, it defaults to 0, that is, a[:3] is equivalent to a[0:3]
    When j is defaulted, it defaults to len(alist), that is, a[1:] is equivalent to a[1:10]
    When i and j are both default, a[:] is equivalent to a complete copy of a

    b = a[i:j:s] In this format, i and j are the same as above, but s represents step, and the default is 1.
    So a[i:j:1] is equivalent to a[i:j]
    When s<0, when i is defaulted, the default is -1. When j is defaulted, the default is -len(a)-1
    So a[::-1] is equivalent to a[-1:-len(a)-1:-1], that is, copying from the last element to the first element. So you see something in reverse order.

    If you still don’t understand, test what I said and you will understand

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 11:46:13

    This is a special usage of python’s slice notation. However, it is recommended not to remember this, it is best to use it like this:

    reversed([1, 2, 3, 4, 5])
    

    reply
    0
  • Cancelreply