如何迭代一个列表,一次访问两个索引并在每次迭代后移动一个索引时间?

Kra*_*r67 2 python loops list

我有一个这样的列表:

a_list = [1,2,3,4,5,6,7,8]
Run Code Online (Sandbox Code Playgroud)

如何迭代它以产生下面的输出?

1,2
2,3
3,4
4,5
5,6
...
Run Code Online (Sandbox Code Playgroud)

谢谢

fla*_*kes 6

您可以使用在起点和终点处带有偏移量的 zip:

print(list(zip(a_list[:-1], a_list[1:])))
Run Code Online (Sandbox Code Playgroud)

稍微灵活的解决方案,不依赖列表语法。

def special_read(data):
    last = None
    for curr in data:
        if last is not None:
            yield last, curr
        last = curr

...

for a, b in special_read(a_list):
    print(a, b)
Run Code Online (Sandbox Code Playgroud)

要使其适用于可变大小的窗口,您可以使用双端队列。这充当环形缓冲区,当它超过窗口大小时会覆盖自身:

import collections

def window(data, size=2):
    queue = collections.deque(maxlen=size)
    for i in data:
        queue.append(i)
        if len(queue) == size:
            yield (*queue,)

for w in window([1,2,3,4,5,6,7,8], size=3):
    print(w)
Run Code Online (Sandbox Code Playgroud)
(1, 2, 3)
(2, 3, 4)
(3, 4, 5)
(4, 5, 6)
(5, 6, 7)
(6, 7, 8)
Run Code Online (Sandbox Code Playgroud)