How can I reverse a list in Python?

后端 未结 30 3220
既然无缘
既然无缘 2020-11-21 22:32

How can I do the following in Python?

array = [0, 10, 20, 40]
for (i = array.length() - 1; i >= 0; i--)

I need to have the elements of a

30条回答
  •  暖寄归人
    2020-11-21 23:25

    You can also use the bitwise complement of the array index to step through the array in reverse:

    >>> array = [0, 10, 20, 40]
    >>> [array[~i] for i, _ in enumerate(array)]
    [40, 20, 10, 0]
    

    Whatever you do, don't do it this way ;)

提交回复
热议问题