Another itertool function?
Raymond Hettinger
vze4rx4y at verizon.net
Tue Apr 29 02:37:52 EDT 2003
[Magnus Lie Hetland]
> The need for the following function just cropped up in a parser I'm
> writing; it seems sufficiently general to perhaps be a candidate for
> itertools -- and I can't see any way of implementing it with the
> current itertools functions:
Okay, I tried it and the result was horrible:
def weave(*iterables):
"Works perfectly except fails to terminate"
return ifilter(None, imap(type(chain([])).next,
cycle(imap(chain, iterables, repeat(repeat(None))))))
>
> def weave(*iterables):
> iterables = map(iter, iterables)
> while iterables:
> for it in iterables[:]:
> try:
> yield it.next()
> except StopIteration:
> iterables.remove(it)
>
> Another possible name (which is a bit more unwieldy) would be
> 'roundrobin'.
I find this name to be the most descriptive.
> I expect there would have to be more use-cases to justify it, but I
> just thought I'd air the idea...
Probably there should be more use cases.
It does seem to be a general purpose tool
for combining iterators.
Here's another idea that was submitted:
def windowed(iterable, group=2):
"returns (i[0], i[1], ... i[group-1]), (i[1], i[2], ... i[group]), ..."
it = iter(iterable)
result = []
while True:
result.pop(0)
result.append(it.next())
if len(result) == group:
yield group
Raymond Hettinger
More information about the Python-list
mailing list