Python get N elements from a list at a time using

2019-08-22 05:34发布

问题:

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?

回答1:

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



回答2:

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


回答3:

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


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


回答5:

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