要将Python中的列表进行反转,有很多方法。以下列出我能想到的常见的几种并进行简单的比较。
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import timeit
a = [1,2,3,4,5]
def func1(a):
b = []
max = len(a)
for i in xrange(max):
b.append(a[max-1-i])
return b
def func2(a):
max = len(a)
for i in xrange(max/2):
a[i], a[max-i-1] = a[max-i-1], a[i]
return a
if __name__ == '__main__':
# 1. 最常见的方法,进行遍历并倒序重排
print 'after func1, a is ', func1(a)
# 2. 交换头尾元素位置
print 'after func2, a is ', func2(a)
# 3. 调用List built-in函数reverse
a = [1,2,3,4,5]
a.reverse()
print 'after a.reverse, a is ', a
# 4. 调用List built-in函数sort
a = [1,2,3,4,5]
a.sort(reverse=True)
print 'after a.sort, a is ', a
# 5. 利用List slice,返回倒序的List
a = [1,2,3,4,5]
print a[-1:-6:-1]
# 6. 原理同5,写法不同
print a[::-1]
# 7. 使用匿名函数来进行倒序
g = lambda x,y: y.extend([x[len(x)-1-i] for i in xrange(len(a))])
b = []
g(a, b)
print b
t = timeit.Timer('func1(a)', 'from __main__ import func1; a = [1,2,3,4,5]')
print 'func1 takes ', t.timeit()
t = timeit.Timer('func2(a)', 'from __main__ import func2; a = [1,2,3,4,5]')
print 'func2 takes ', t.timeit()
t = timeit.Timer('a.reverse()', 'a = [1,2,3,4,5]')
print 'a.reverse takes ', t.timeit()
t = timeit.Timer('a.sort(reverse=True)', 'a = [1,2,3,4,5]')
print 'a.sort takes ', t.timeit()
t = timeit.Timer('a[-1:-6:-1]', 'a = [1,2,3,4,5]')
print 'a[-1:-6:-1] takes ', t.timeit()
t = timeit.Timer('a[::-1]', 'a = [1,2,3,4,5]')
print 'a[::-1] takes ', t.timeit()
t = timeit.Timer('g = lambda x,y: y.extend([x[len(x)-1-i] for i in xrange(len(a))]);g(a, b)', 'a = [1,2,3,4,5]; b = []')
print 'lambda takes ', t.timeit()
Output:
after func1, a is [5, 4, 3, 2, 1]
after func2, a is [5, 4, 3, 2, 1]
after a.reverse, a is [5, 4, 3, 2, 1]
after a.sort, a is [5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
func1 takes 3.53492333161
func2 takes 2.01102125305
a.reverse takes 0.12254191834
a.sort takes 0.987050491478
a[-1:-6:-1] takes 0.319906464807
a[::-1] takes 0.288911484982
lambda takes 2.6436039154
可以看到,内建函数reverse最节省时间,也就意味着reverse性能最好。
其实从Python的源代码层面来看,在指针级别对List进行反转,而不需要反复新建List,甚至反复申请新的变量,是非常有效率的一种方法。有空的时候我会补充上源码细节。
欢迎提问和补充!