How can I reverse a list in Python?

2018-12-31 08:58发布

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 an array, but from the end to the beginning.

标签: python list
30条回答
心情的温度
2楼-- · 2018-12-31 09:12

I think that the best way to reverse a list in Python is to do:

a = [1,2,3,4]
a = a[::-1]
print(a)
>>> [4,3,2,1]

The job is done, and now you have a reversed list.

查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 09:12

Use the reversed function as follow and print it

>>> for element in reversed(your_array):
...     print element
查看更多
流年柔荑漫光年
4楼-- · 2018-12-31 09:12
def reverse(my_list):
  L = len(my_list)
  for i in range(L/2):
    my_list[i], my_list[L-i - 1] = my_list[L-i-1], my_list[i]
  return my_list
查看更多
何处买醉
5楼-- · 2018-12-31 09:13

This is to duplicate the list:

L = [0,10,20,40]
p = L[::-1]  #  Here p will be having reversed list

This is to reverse the list in-place:

L.reverse() # Here L will be reversed in-place (no new list made)
查看更多
低头抚发
6楼-- · 2018-12-31 09:13

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.

查看更多
十年一品温如言
7楼-- · 2018-12-31 09:14

With reversed and list:

>>> list1 = [1,2,3]
>>> reversed_list = list(reversed(list1))
>>> reversed_list
>>> [3, 2, 1]
查看更多
登录 后发表回答