What is the nicest way of splitting this:
tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
into this:
tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
Assuming that the input always has an even number of values.
What is the nicest way of splitting this:
tuple = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
into this:
tuples = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
Assuming that the input always has an even number of values.
zip()
is your friend:
t = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
zip(t[::2], t[1::2])
Here's a general recipe for any-size chunk, if it might not always be 2:
def chunk(seq, n):
return [seq[i:i+n] for i in range(0, len(seq), n)]
chunks= chunk(tuples, 2)
Or, if you enjoy iterators:
def iterchunk(iterable, n):
it= iter(iterable)
while True:
chunk= []
try:
for i in range(n):
chunk.append(it.next())
except StopIteration:
break
finally:
if len(chunk)!=0:
yield tuple(chunk)
Or, using itertools
(see the recipe for grouper
):
from itertools import izip
def group2(iterable):
args = [iter(iterable)] * 2
return izip(*args)
tuples = [ab for ab in group2(tuple)]