Imagine I have a list like this:
a = [1,2,3,4,5,6]
Using a lambda function, I would like to return two elements at a time, so the result would be:
res = [[1,2], [2,3], [3,4], [4,5], [5,6]]
Any suggestions?
Imagine I have a list like this:
a = [1,2,3,4,5,6]
Using a lambda function, I would like to return two elements at a time, so the result would be:
res = [[1,2], [2,3], [3,4], [4,5], [5,6]]
Any suggestions?
>>> import itertools
>>> itertools.izip(a, itertools.islice(a,1,None))
This avoids creating a copy of your original list, which may be relevant if it's very big.
>>> zip(a, a[1:])
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
For arbitrary n
:
>>> n = 3
>>> zip(*(a[i:] for i in range(n)))
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]
>>> map(lambda i:a[i:i+2], range(len(a)-1))
[[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
One option:
a = [1, 2, 3, 4, 5, 6]
[a[i:i+2] for i in range(len(a)-1)] # => [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
I recommend using a generator.
>>> a = [1,2,3,4,5,6]
>>> g=([a[i:i+2]] for i in range(len(a)-1))
you can always grab the list if you want:
>>> list(g)
[[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]