Skip to content Skip to sidebar Skip to footer

Python Get N Elements From A List At A Time Using Lambda

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

Solution 1:

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

For arbitrary n:

>>>n = 3>>>zip(*(a[i:] for i inrange(n)))
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]

Solution 2:

>>>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.

Solution 3:

>>> map(lambda i:a[i:i+2], range(len(a)-1))
[[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]

Solution 4:

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]]

Solution 5:

I recommend using a generator.

>>>a = [1,2,3,4,5,6]>>> g=([a[i:i+2]] for i inrange(len(a)-1))

you can always grab the list if you want:

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

Post a Comment for "Python Get N Elements From A List At A Time Using Lambda"