I need to make tuple of list with 2 items.
For example if I have list range(10)
I need to make tuple like this:
[(0,1),(2,3),(4,5),(6,7),(8,9)]
How can I implement that?
I need to make tuple of list with 2 items.
For example if I have list range(10)
I need to make tuple like this:
[(0,1),(2,3),(4,5),(6,7),(8,9)]
How can I implement that?
Many different ways. Just to show off a few:
As list comprehension, where l is a sequence (i.e. integer indexes): [(l[i], l[i+1]) for i in range(0,len(l),2)]
As generator function, works for all iterables:
def some_meaningful_name(it):
it = iter(it)
while True:
yield next(it), next(it)
Naive via list slicing (sucksy performance for larger lists) and copying, again using list comprehension: [pair for pair in zip(l[::2],l[1::2])]
.
I like the second best, and it's propably the most pythonic and generic (and since it's a generator, it runs in constant space).
See the grouper recipe from the itertools
docs:
from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
"""
>>> grouper(3, 'ABCDEFG', 'x')
["ABC", "DEF", "Gxx"]
"""
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
This means that you can do:
[(el[0], el[1]) for el in grouper(2, range(10))]
Or more generally:
[(el[0], el[1]) for el in grouper(2, elements)]
Can also be done with numpy:
import numpy
elements = range(10)
elements = [tuple(e) for e in numpy.array(elements).reshape(-1,2).tolist()]
# [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]