Opposite of zip(*[iter(s)]*n)
Question:
Dividing a list into equal chunks is neatly done using the zip(*[iter(s)]*n)
idiom. Is there a nice way of undoing it?
For example, if I have the following code:
>>> s = [3,4,1,2]
>>> zip(*[iter(s)]*2)
[(3, 4), (1, 2)]
Is there some function func([(3,4),(1,2)]
that will yield [3,4,1,2]
as the output?
Edit:
Timing and more solutions can be found in the question linked to by Dominic Kexel below.
Answers:
There is itertools.chain.from_iterable
>>> import itertools
>>> s = [(3, 4), (1, 2)]
>>> list(itertools.chain.from_iterable(s))
[3, 4, 1, 2]
However you could also use a nested list comprehension.
>>> s = [(3, 4), (1, 2)]
>>> [i for sub in s for i in sub]
[3, 4, 1, 2]
You can use reduce:
>>> import operator
>>> reduce(operator.add, [(3,4),(1,2)])
(3, 4, 1, 2)
Dividing a list into equal chunks is neatly done using the zip(*[iter(s)]*n)
idiom. Is there a nice way of undoing it?
For example, if I have the following code:
>>> s = [3,4,1,2]
>>> zip(*[iter(s)]*2)
[(3, 4), (1, 2)]
Is there some function func([(3,4),(1,2)]
that will yield [3,4,1,2]
as the output?
Edit:
Timing and more solutions can be found in the question linked to by Dominic Kexel below.
There is itertools.chain.from_iterable
>>> import itertools
>>> s = [(3, 4), (1, 2)]
>>> list(itertools.chain.from_iterable(s))
[3, 4, 1, 2]
However you could also use a nested list comprehension.
>>> s = [(3, 4), (1, 2)]
>>> [i for sub in s for i in sub]
[3, 4, 1, 2]
You can use reduce:
>>> import operator
>>> reduce(operator.add, [(3,4),(1,2)])
(3, 4, 1, 2)