python列表反转

使用reverse来让列表反转特别方便, 没事自己写了几种方式

In [59]: def reverse(nums):
length = len(nums)
for i in range(length-1):
nums.insert(length-i-1, nums.pop(0))
print nums
....: In [60]: In [60]: In [60]: a = range(5) In [61]: reverse(a)
[1, 2, 3, 4, 0]
[2, 3, 4, 1, 0]
[3, 4, 2, 1, 0]
[4, 3, 2, 1, 0] In [62]: a
Out[62]: [4, 3, 2, 1, 0] In [63]:

根据结果能看出, insert操作的执行顺序是先删除, 后插入

In [67]: def reverse(nums):
i, j = 0, len(nums)-1
while i < j:
nums[i], nums[j] = nums[j], nums[i]
i, j = i+1, j-1
print nums In [69]: a = range(5) In [70]: a
Out[70]: [0, 1, 2, 3, 4] In [71]: In [71]: reverse(a)
[4, 1, 2, 3, 0]
[4, 3, 2, 1, 0] In [72]: a
Out[72]: [4, 3, 2, 1, 0] In [73]:

以上两种都是原地操作

In [78]: a
Out[78]: [0, 1, 2, 3, 4] In [79]: In [79]: b = [] In [80]: def reverse(nums):
....: for i in nums:
....: b.insert(0, i)
....: In [81]: In [81]: reverse(a) In [82]: In [82]: b
Out[82]: [4, 3, 2, 1, 0] In [83]: id(a)
Out[83]: 140434157093160 In [84]: id(b)
Out[84]: 140434157062984 In [85]:
上一篇:js 随机星星 document.createElement(); setAttribute()


下一篇:redhat Enterprise Linux 6 VNC安装