Python 3.8:遍历第一个和第二个元素,然后是第二个和第三个,依此类推

Python 3.8: Iterate over 1st and 2nd element, then 2nd and 3rd and so on

我想通过创建一个范围来比较列表中的某些数字与另一个列表中的值。 像这样:

r = np.arange(0, 20, 2)

现在,r 是一个如下所示的数组:

array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])

现在,我想使用一个从 r 的前两个元素开始的 for 循环,并创建一个范围,以便在第一次迭代时考虑第一个和第二个元素,然后在第二次迭代中,考虑第二个和第三个元素。

因此每次迭代看起来像这样:

range(0,2)
range(2,4)
range(4,6)
range(6,8)

等等。

有这样循环的函数吗?

我不想迭代非重叠块,即

range(0,2)
range(4,6) # This is not what I want
range(6,8)

等等。

更新: 从 Python 3.10 开始,此功能是内置的。使用 itertools.pairwise().

itertools 底部有一个很好的食谱,叫做“pairwise”:

from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

用法示例:

for x, y in pairwise([1,2,3,4]):
     print(x, y)

1 2
2 3
3 4