python循环遍历列表中的n个连续项

时间:2013-03-13 20:49:50

标签: python

我需要遍历列表中的n个连续元素。 例如:

data = [1,2,3,4,5,6,7]

我需要过去:

1 2
2 3
3 4
4 5

或:

1 2 3
2 3 4
3 4 5
4 5 6

是否有拉链功能吗?

6 个答案:

答案 0 :(得分:5)

我不确定你到底在想什么,但试试这个:

data = [1, 2, 3, 4, 5, 6, 7]

n = 3

[data[i:i+n] for i in range(len(data) - n + 1)]

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

或者:

f = lambda data, n: [data[i:i+n] for i in range(len(data) - n + 1)]

for x, y, z in f([1, 2, 3, 4, 5, 6, 7], 3):
    print x, y, z

答案 1 :(得分:3)

假设您总是为列表或其他序列执行此操作,并且不需要使用任意迭代:

def group(seq, n):
    return (seq[i:i+n] for i in range(len(seq)-n+1))

示例:

>>> list(group([1,2,3,4,5,6,7], 2))
[[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]]
>>> list(group([1,2,3,4,5,6,7], 3))
[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7]]

如果您需要为任意迭代(可能不支持len()或切片)执行此操作,您可以调整pairwise recipe

from itertools import tee, izip

def group(iterable, n):
    "group(s, 3) -> (s0, s1, s2), (s1, s2, s3), (s2, s3, s4), ..."
    itrs = tee(iterable, n)
    for i in range(1, n):
        for itr in itrs[i:]:
            next(itr, None)
    return izip(*itrs)

>>> list(group(iter([1,2,3,4,5,6,7]), 2))
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)]
>>> list(group(iter([1,2,3,4,5,6,7]), 3))
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)]

答案 2 :(得分:3)

具体答案:

>>> zip(data,data[1:])
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)]

一般答案:

>>> def consecutives(data,per_set):
...   return zip(*[data[n:] for n in range(per_set)])
...
>>> consecutives(range(1,8),2)
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)]
>>> consecutives(range(1,8),3)
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)]
>>> consecutives(range(1,8),4)
[(1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6), (4, 5, 6, 7)]

答案 3 :(得分:0)

取决于您是要迭代子列表还是平面列表:

from itertools import chain
for x in chain(*[ a[i:i+n] for i in xrange(len(a)-n+1) ]):
    print x

或者:

for x in [ a[i:i+n] for i in xrange(len(a)-n+1) ]:
    print x

答案 4 :(得分:0)

可能不是最好的方法,但仍然有用:

>>> data = [1,2,3,4,5,6,7]
>>> map(None,data[:-1],data[1:])
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)]

>>> map(None,data[:-2],data[1:-1],data[2:])
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)]

答案 5 :(得分:-4)

这是一个相当简单的自我编程任务。我不认为有一个预先实现的功能。

def func(arr,n):
    i = 0
    while i+n < len(arr):
       for range(i,i+n):
          .... make stuff here....
       i = i + 1