Python 在不使用列表长度的情况下迭代子列表

Python 在不使用列表长度的情况下迭代子列表,python,list,iteration,Python,List,Iteration,我有一个列表,我需要对3个元素的连续(和重叠)组进行一些处理: 我可以用: 范围内的i(len(things)-2): 过程(事物[i:i+3]) 例如: things=[0, 1, 2, 3, 4, 5, 6, 7] 我想处理: [0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7] 但是,有没有一种聪明(但可读)的方法可以不用显式地使用len(things)?另一种方法可以是: for i in things[0

我有一个列表,我需要对3个元素的连续(和重叠)组进行一些处理:

我可以用:

范围内的i(len(things)-2):
过程(事物[i:i+3])
例如:

things=[0, 1, 2, 3, 4, 5, 6, 7]
我想处理:

[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]

但是,有没有一种聪明(但可读)的方法可以不用显式地使用
len(things)

另一种方法可以是:

for i in things[0:-2]:
    a=things.index(i)
    process(things[a:a+3])

让我们尝试使用
enumerate
,这里
len(things[i:i+len_])==len_
是删除在迭代结束时累积的大小不均匀的列表

len_ = 3

[things[i : i+len_] for i, j in enumerate(things) if len(things[i : i+len_]) == len_]

[[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]]


是的,你要找的是所谓的滑动/移动窗口。实现这一点的方法多种多样,但最简单的方法是使用
itertools
中的
tee()
islice()
函数。使用此函数,您可以定义如下所示的
window()
函数,默认窗口大小为2

import itertools

def window(iterable, n=2):
    iters = itertools.tee(iterable, n)
    for i, it in enumerate(iters):
        next(itertools.islice(it, i, i), None)
    return zip(*iters)
然后你就可以把它当作

>>> things=[0, 1, 2, 3, 4, 5, 6, 7]
>>> list(window(things, n = 3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)]
>>> for elem in window(things, n = 3):
...     print(elem)
... 
(0, 1, 2)
(1, 2, 3)
(2, 3, 4)
(3, 4, 5)
(4, 5, 6)
(5, 6, 7)
编辑:一次性使用更简单的选项

>>> list(zip(things, things[1:], things[2:]))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)]

你能展示一些示例输入和预期输出吗?有点过分了,因为我在代码中只需要一次,但请接受我的投票:)@xenoid你可以一次性使用类似于
zip(things,things[1:],things[2:])
。我编辑了这篇文章来展示结果。@SigmalEpsilon这确实是你的解决方案让我想到的,而且我在两端都有特殊处理,可以通过在三个列表中添加足够的位来很好地实现。我唯一担心的是这会复制列表(IRL将是100到1000个元素)。至少这样我就不用写我自己的答案了:)
>>> list(zip(things, things[1:], things[2:]))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)]