蟒蛇循环在列表中的n个连续项目
问题描述:
我需要迭代列表中的n个连续元素。 例如:蟒蛇循环在列表中的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
有拉链功能做到这一点?
答
这是一个相当简单的任务来编程自己。我不认为有一个预先设定的功能来做到这一点。
def func(arr,n):
i = 0
while i+n < len(arr):
for range(i,i+n):
.... make stuff here....
i = i + 1
答
根据您是否要遍历子列表或一个平坦的列表:
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
答
我不知道你到底是什么寻找,但试试这个:
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
答
可能不是最好的方式,但仍然有用:
>>> 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)]
+0
现在我意识到zip(* args)和map(None,* args)做同样的事情,至少在这种情况下。 – 2013-03-13 21:00:33
答
假设你总是在做这个列表或其他序列,它不需要与任意iterables工作:
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)]
答
明确的答案:
>>> 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)]
到目前为止,我有这个我正在寻找一个班轮: def loopover(listk,n): l1 = []; s = 0 while(len(listk)): for i in range(0,len(listk)): l1.append(listk [s:n]); s = s + 1; N = N + 1; – mparida 2013-03-13 20:56:13