Python 减去列表中的当前项和上一项
写一个循环并记住上一个循环是很常见的 我想要一台能为我做这件事的发电机。比如:Python 减去列表中的当前项和上一项,python,Python,写一个循环并记住上一个循环是很常见的 我想要一台能为我做这件事的发电机。比如: 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
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]
- 这个手术的好名字是什么
- 写这篇文章的更好方法是什么
- 是否有类似的内置函数
- 尝试使用“地图”并没有简化它。这是什么意思
>>> L = [0, 3, 4, 10, 2, 3]
>>> [b - a for a, b in pairwise(L)]
[3, 1, 6, -8, 1]
[编辑]
同样,这也有效(Python<3):
print语句中使用的构造称为“列表理解”。列表理解已经非常简单,这是显而易见的自然方式。从这一点到更加晦涩的
地图
表明你想得太多了。生成器的功能也已经简单明了了。它看起来像,当n为2时,又称ngram。你有多聪明
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]
>>> map(lambda(a, b):b - a, pairwise(L))
[y - x for x,y in zip(L,L[1:])]