Reputation: 946
If I have the big list A = [1,2,3,4,5,6,7,8,9,10] and I have sub lists of 3 elements e.g
B = [1,2,3]
I want to slide 1 step forward according to the A list so B becomes [2,3,4] - is there a smooth way to do this? Or do i just have to pop the first element of B and then append the proper element from A?
Thanks!
EDIT: My answer B = A[i:i+3] Where you can increase 'i' if you want to view forward by 'i' steps.
Upvotes: 1
Views: 403
Reputation: 15864
Using itertools
:
>>> from itertools import islice, izip
>>> A = [1,2,3,4,5,6,7,8,9,10]
>>> for l in izip(*(islice(A, x, None) for x in xrange(3))):
... print list(l)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 10]
islice(A, x, None)
creates an iterator over A[x:]
.
Upvotes: 0
Reputation: 304393
>>> A = [1,2,3,4,5,6,7,8,9,10]
>>> for B in (A[i - 3: i] for i in range(3, len(A) + 1)):
... print B
...
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 10]
Upvotes: 0
Reputation: 41
for i in range(len(a)-2):
b = a[i:i+3]
print b
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 10]
You can make more generally.
Upvotes: 1
Reputation: 25974
You can make A
a deque
:
from collections import deque
A = deque(range(1,11))
And B
can be a view of the first 3 elements of A
. When you need to "slide", rotate A
to the left.
A
Out[71]: deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
from itertools import islice #deques do not support slicing notation
B = list(islice(A,3))
B
Out[74]: [1, 2, 3]
A.rotate(-1)
B = list(islice(A,3))
B
Out[77]: [2, 3, 4]
Upvotes: 3