In need of a binge-and-purge idiom
Magnus Lie Hetland
mlh at furu.idi.ntnu.no
Sun Mar 23 18:51:29 EST 2003
In article <mailman.1048447384.30411.python-list at python.org>, Tim Peters wrote:
>[Magnus Lie Hetland]
>> Maybe not the best name, but it somehow describes what's going on...
>> So...
>>
>> I've noticed that I use the following in several contexts:
A little fix...
>> chunk = []
>> for element in iterable:
>> if isSeparator(element):
if chunk:
>> doSomething(chunk)
>> chunk = []
else:
chunk.append(element)
>> if chunk:
>> doSomething(chunk)
>> chunk = []
The original was written in a hurry :]
>Since chunk is initialized to an empty list, the if clause in the loop can
>never evaluate to true, so this is equivalent to
>
> chunk = []
> for element in iterable:
> isSeparator(element)
Yup.
>All variations of the code later in the msg suffer the same problem. As a
>result, I've got no idea what you intend the code to do. Does calling
>isSeparator(element), or <shudder> the process of iterating over iterable,
>mutate chunk as a side effect? If so, "yuck" comes to mind.
No, sorry -- I just forgot parts of the code :)
>If the code made sense <wink>, something like
>
>def terminated_iterator(iterable, a_seperator):
> for element in iterable:
> yield element
> yield a_separator
>
>would produce the original sequence, then tack a_separator on to the end.
Yes, that's what I've done before (e.g. in an example in my book).
Maybe that is the best way of doing it.
[snip]
>WRT the preceding,
>
> for element in terminated_iterator(iterable, seperator):
>
>gets that effect.
Indeed.
> More generally,
>
>def concat(*seqs):
> "Generate all the elements of all the argument iterables."
> for seq in seqs:
> for x in seq:
> yield x
>
>and then, e.g.,
>
> for element in concat(iterable, [seperator]):
Yes. I posted something similar to that when discussing itertools
previously. I guess I was (now) mainly looking for some basic use of
control structures that I had overlooked.
Anyway, thanks for the input.
--
Magnus Lie Hetland "Nothing shocks me. I'm a scientist."
http://hetland.org -- Indiana Jones
More information about the Python-list
mailing list