1. list comprehension 列表推导式,是一种很方便的遍历方式,通常速度会比for loop快很多。
常规的nested loop:
def test1():
#nested loop
l = []
for x in [1,2,3,4,5,6,7,8,9,10]:
for y in [1,2,3,4,5,6,7,8,9,10]:
l.append(x*y)
return l
使用list comprehension代替:
def test2():
return [x*y for x in [1,2,3,4,5,6,7,8,9,10] for y in [1,2,3,4,5,6,7,8,9,10]]
对于上述的代码进行运行时间的测试,
from timeit import Timer
print test1()
print test2()
t1 = Timer('test1()', 'from __main__ import test1')
t2 = Timer('test2()', 'from __main__ import test2')
print t1
print t2
print t1.timeit(10000)
print t2.timeit(10000)
##############
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
<timeit.Timer instance at 0x0000000001ED1BC8>
<timeit.Timer instance at 0x0000000001F218C8>
0.40161077232
0.234277149127
可以很明显看出来list comprehension要比普通的for loop快上很多。
2. generator expression
对于generator expression,和list comprehension相似,更改了中括号为小括号。但是更加节省了空间,效率更高,返回一个生成器对象,而不是一个list。更加的是,返回的生成器对象有提供iterator的功能,可以用next方法来获得item。
对于生成器对象和迭代的区别,再另一篇博客中有提到。下面重复一下例子。
g = (x*2 for x in range(5))
print g
# <generator object <genexpr> at 0x000000000207EEA0>
print g.next()
# 0
print g.next()
# 2
print g.next()
# 4