写一个循环并记住前面的内容是很常见的。
我想要一个能为我做这件事的发电机。像这样的东西:
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 ”并没有简化它。做什么?
最佳答案
[y - x for x,y in zip(L,L[1:])]
关于python - 减去列表中的当前项和上一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4029436/