I can do it by making use of the list indexes ...
lst =[1,2,3,4,5,6]
[ [lst[i] , lst[i+1]] for i in range( len(lst) - 1 )]
or:
lst =[1,2,3,4,5,6]
for i in range(len(lst)-1):
entities.append([lst[i],lst[i+1]])
But is there a smarter way? Maybe using iterators? What about performance?
For a general solution (since you asked for couples, triples, etc.), use itertools.tee
:
from itertools import tee
def adjacent_tuples(iterable, n=2):
iterators = tee(iterable, n)
for i, iterator in enumerate(iterators):
for j in range(i):
next(iterator)
return zip(*iterators)
This uses a minimum of memory and works for any length of tuples:
>>> list(adjacent_tuples(range(8), 4))
[(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6), (4, 5, 6, 7)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With