[Python-ideas] Add 'interleave' function to itertools?
Andrew Barnert
abarnert at yahoo.com
Wed Aug 7 23:00:47 CEST 2013
On Aug 7, 2013, at 13:02, Serhiy Storchaka <storchaka at gmail.com> wrote:
> 07.08.13 22:19, Vito De Tullio написав(ла):
>> MRAB wrote:
>>
>>> def interleave(*iterables):
>>> """Return a interleave object whose .__next__() method returns an
>>> element from each iterable argument in turn. The .__next__()
>>> method continues until the shortest iterable in the argument
>>> sequence is exhausted and then it raises StopIteration.
>>> """
>>>
>>> sources = [iter(iterable) for iterable in iterables]
>>>
>>> try:
>>> while True:
>>> for iterable in sources:
>>> yield next(iterable)
>>> except StopIteration:
>>> pass
>>
>> isn't something like
>>
>> def interleave(*iterables):
>> for zipped_iterables in zip(*iterables):
>> yield from zipped_iterables
>>
>> sufficient?
>
> chain.from_iterable(zip(*iterables))
Yet another reason why chain.from_iterable should be more discoverable. The operation is obviously just flattening/chaining a zip, and the only reason that isn't the obvious code for many people is that they don't know how to flatten.
More information about the Python-ideas
mailing list