列表中相邻元素之间的差异

37
我有一个列表,我想找出相邻元素之间的差异:
可能重复:
Python - 列表元素之间的差异
a = [0, 4, 10, 100]
find_diff(a)
>>> [4,6,90]

你如何编写find_diff()函数?我可以用"for"迭代器编写它,但我相信有非常简单的方法可以用一行代码实现。


嗯,我本来想接受第一个答案的,但现在看到它被删除了。 - gok
正如它应该的那样,因为这个问题完全相同 - Matt Ball
那我应该删除这个问题吗?在提问之前我没有在搜索中找到那个。 - gok
2
不要删除它。这将被关闭为重复,因此不能再添加答案。通常,拥有多个指向单个规范问答的副本是很好的。由于提出问题有多种方式,因此具有多个(措辞不同)指向主要问答的问题可以使将来更容易找到主要问答。 - Matt Ball
3个回答

79

您可以利用enumeratezip列表推导式

>>> 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

19

使用 itertools.pairwise(Python 3.10+):

>>> from itertools import pairwise
>>> a = [0, 4, 10, 100]
>>> [y - x for x, y in pairwise(a)]
[4, 6, 90]

对于Python 3.9及更早版本,您可以使用itertools文档中的“pairwise”配方: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)

1
这完全没有必要。参见Python - Differences between elements of a list - Matt Ball
15
许多迭代器可能被称为“不必要的”,但是一旦定义了它们,它们对于常见的习惯用法非常有用。为什么要让读者费解两个切片的 zip,当我们可以给这个想法分配一个有用的名称,比如 pairwise。我认为我并不孤单,因为我直接从文档中引用了这个例子。 - Steven Rumbalski
1
+!这个版本适用于任意生成器,无法进行切片/索引。 - avmohan
1
此函数可在 Python 3.10 及以上版本的 itertools 中使用。 - arjunsiva

6
[x - a[i-1] if i else None for i, x in enumerate(a)][1:]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接