# Python – 列表元素之间的差异

` `>>> t [1, 3, 6] >>> [ji for i, j in zip(t[:-1], t[1:])] # or use itertools.izip in py2k [2, 3]` `

` `v = numpy.diff(t)` `

` `>>> t = [1, 3, 6] >>> v = [t[i+1]-t[i] for i in range(len(t)-1)] >>> v [2, 3]` `

` `from itertools import tee # python2 only: #from itertools import izip as zip def differences(seq): iterable, copied = tee(seq) next(copied) for x, y in zip(iterable, copied): yield y - x` `

` `from itertools import islice def differences(seq): nexts = islice(seq, 1, len(seq)) for x, y in zip(seq, nexts): yield y - x` `

` `def differences(seq): iterable = iter(seq) prev = next(iterable) for element in iterable: yield element - prev prev = element` `

` `In [12]: L = range(10**6) In [13]: from collections import deque In [15]: %timeit deque(differences_tee(L), maxlen=0) 10 loops, best of 3: 122 ms per loop In [16]: %timeit deque(differences_islice(L), maxlen=0) 10 loops, best of 3: 127 ms per loop In [17]: %timeit deque(differences_no_it(L), maxlen=0) 10 loops, best of 3: 89.9 ms per loop` `

` `In [18]: %timeit [x[1] - x[0] for x in zip(L[1:], L)] 10 loops, best of 3: 163 ms per loop In [19]: %timeit [L[i+1]-L[i] for i in range(len(L)-1)] 1 loops, best of 3: 395 ms per loop In [20]: import numpy as np In [21]: %timeit np.diff(L) 1 loops, best of 3: 479 ms per loop In [35]: %%timeit ...: res = [] ...: for i in range(len(L) - 1): ...: res.append(L[i+1] - L[i]) ...: 1 loops, best of 3: 234 ms per loop` `

• `zip(L[1:], L)`等同于`zip(L[1:], L[:-1])`因为`zip`已经在最短的input上终止，但是它避免了`L`的整个副本。
• 通过索引访问单个元素非常缓慢，因为每个索引访问都是在python中的方法调用
• `numpy.diff`慢，因为它必须首先将`list`转换为一个`ndarray` 。 很明显，如果你一个`ndarray` 开始 ，它会快得多：

` `In [22]: arr = np.array(L) In [23]: %timeit np.diff(arr) 100 loops, best of 3: 3.02 ms per loop` `

` `v = [x[1]-x[0] for x in zip(t[1:],t[:-1])]` `

function性方法：

` `>>> import operator >>> a = [1,3,5,7,11,13,17,21] >>> map(operator.sub, a[1:], a[:-1]) [2, 2, 2, 4, 2, 4, 4]` `

` `>>> import operator, itertools >>> g1,g2 = itertools.tee((x*x for x in xrange(5)),2) >>> list(itertools.imap(operator.sub, itertools.islice(g1,1,None), g2)) [1, 3, 5, 7]` `

` `>>> [a[i+1]-a[i] for i in xrange(len(a)-1)] [2, 2, 2, 4, 2, 4, 4]` `

` `>>>v = [1,2,3,4,5] >>>[v[i] - v[i-1] for i, value in enumerate(v[1:], 1)] [1, 1, 1, 1]` `