Re: Feature Proposal: Sequence .join method
- From: David Murmann <david.murmann@xxxxxxxxxxxxxx>
- Date: Fri, 30 Sep 2005 19:06:40 +0200
Michael Spencer wrote:
Terry Reedy wrote:"David Murmann" <david.murmann@xxxxxxxxxxxxxx> wrote in message news:3q3pt9Fd7pklU1@xxxxxxxxxxxxxxxxx
def join(sep, seq): return reduce(lambda x, y: x + sep + y, seq, type(sep)())
damn, i wanted too much. Proper implementation:
def join(sep, seq): if len(seq): return reduce(lambda x, y: x + sep + y, seq) return type(sep)()
but still short enough
For general use, this is both too general and not general enough.
If len(seq) exists then seq is probably reiterable, in which case it may be possible to determine the output length and preallocate to make the process O(n) instead of O(n**2). I believe str.join does this. A user written join for lists could also. A tuple function could make a list first and then tuple(it) at the end.
If seq is a general (non-empty) iterable, len(seq) may raise an exception even though the reduce would work fine.
Terry J. Reedy
For the general iterable case, you could have something like this:
>>> def interleave(sep, iterable):
... it = iter(iterable)
... next = it.next()
... try:
... while 1:
... item = next
... next = it.next()
... yield item
... yield sep
... except StopIteration:
... yield item
...
>>> list(interleave(100,range(10)))
[0, 100, 1, 100, 2, 100, 3, 100, 4, 100, 5, 100, 6, 100, 7, 100, 8, 100, 9]
Well, as en.karpachov@xxxxxxxx pointed out, there is already itertools.chain which almost does this. In my opinion it could be useful to add an optional keyword argument to it (like "connector" or "link"), which is iterated between the other arguments.
but I can't think of a use for it ;-)
Of course, i have a use case, but i don't know whether this is useful enough to be added to the standard library. (Yet this would be a much smaller change than changing all sequences ;)
thanks for all replies, David. .
- References:
- Re: Feature Proposal: Sequence .join method
- From: David Murmann
- Re: Feature Proposal: Sequence .join method
- From: Michael Spencer
- Re: Feature Proposal: Sequence .join method
- Prev by Date: Re: RELEASED Python 2.4.2 (final)
- Next by Date: Re: RELEASED Python 2.4.2 (final)
- Previous by thread: Re: Feature Proposal: Sequence .join method
- Next by thread: Re: Feature Proposal: Sequence .join method
- Index(es):