我有一个列表,我想找到连续元素之间的区别:
a = [0, 4, 10, 100]
find_diff(a)
>>> [4,6,90]
您如何编写find_diff()函数代码?我可以使用“for”迭代器对其进行编码,但我确信有一种非常简单的方法可以使用简单的单行程序来实现。
答案 0 :(得分:41)
您可以使用enumerate
,zip
和list comprehensions:
>>> a = [0, 4, 10, 100]
# basic enumerate without condition:
>>> [x - a[i - 1] for i, x in enumerate(a)][1:]
[4, 6, 90]
# enumerate with conditional inside the list comprehension:
>>> [x - a[i - 1] for i, x in enumerate(a) if i > 0]
[4, 6, 90]
# the zip version seems more concise and elegant:
>>> [t - s for s, t in zip(a, a[1:])]
[4, 6, 90]
在性能方面,似乎没有太多差异:
In [5]: %timeit [x - a[i - 1] for i, x in enumerate(a)][1:]
1000000 loops, best of 3: 1.34 µs per loop
In [6]: %timeit [x - a[i - 1] for i, x in enumerate(a) if i > 0]
1000000 loops, best of 3: 1.11 µs per loop
In [7]: %timeit [t - s for s, t in zip(a, a[1:])]
1000000 loops, best of 3: 1.1 µs per loop
答案 1 :(得分:16)
使用itertools文档中的recipe for pairwise
:
from itertools import izip, tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
像这样使用:
>>> a = [0, 4, 10, 100]
>>> [y-x for x,y in pairwise(a)]
[4, 6, 90]
答案 2 :(得分:3)
[x - a[i-1] if i else None for i, x in enumerate(a)][1:]