从列表中减去当前项和前一项

11 投票
3 回答
14957 浏览
提问于 2025-04-16 06:08

写循环的时候,记住上一个值是很常见的事情。

我想要一个生成器来帮我完成这个工作。类似这样的:

import operator

def foo(it):
    it = iter(it)
    f = it.next()
    for s in it:
        yield f, s
        f = s

现在进行成对的减法。

L = [0, 3, 4, 10, 2, 3]

print list(foo(L))
print [x[1] - x[0] for x in foo(L)]
print map(lambda x: -operator.sub(*x), foo(L)) # SAME

输出:

[(0, 3), (3, 4), (4, 10), (10, 2), (2, 3)]
[3, 1, 6, -8, 1]
[3, 1, 6, -8, 1]
  • 这个操作有什么好的名字吗?
  • 有没有更好的写法?
  • 有没有内置的函数可以做类似的事情?
  • 尝试使用'map'并没有简化这个过程,那有什么方法可以简化呢?

3 个回答

4

来自itertools的示例:

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)

然后:

>>> L = [0, 3, 4, 10, 2, 3]
>>> [b - a for a, b in pairwise(L)]
[3, 1, 6, -8, 1]

[编辑]

另外,这个也可以用(适用于Python 3之前的版本):

>>> map(lambda(a, b):b - a, pairwise(L))
4
l = [(0,3), (3,4), (4,10), (10,2), (2,3)]
print [(y-x) for (x,y) in l]

输出结果是:[3, 1, 6, -8, 1]

49
[y - x for x,y in zip(L,L[1:])]

这个代码块是一个占位符,里面可能会有一些代码示例或者相关的内容。具体的内容需要根据实际情况来填充。

撰写回答