New (?) suggestion re: 'while x = f(): ...'
Jeff Epler
jepler at unpythonic.net
Wed May 29 09:56:25 EDT 2002
On Wed, May 29, 2002 at 09:10:59AM +0000, Duncan Booth wrote:
> Jeff Epler <jepler at unpythonic.net> wrote in
> news:mailman.1022619227.16027.python-list at python.org:
>
> > and instead of
> > while 1:
> > x = f()
> > if not x: break
> > ...
> > you can write
> > for x in H(f):
> > ...
> >
> > Given suitable names for G() and H() (and I haven't thought of any yet)
> > does anybody favor this over the "pythonic" syntax? Personally, I think
> > I'll stick to doing it in the old-fashioned way, but I wanted to share
> > my idea with the world...
>
> 'H' is spelled 'iter' and already exists.
Not quite -- H will stop on "any false value", while iter(f, "") will
stop on a single value.
Now, if iter would take a function as a second argument...
def myiter(f, g):
if callable(g):
while 1:
v = f()
if g(v): break
yield v
else:
while 1:
v = f()
if v==g: break
yield v
then myiter(f, lambda x: not x) would be the equivalen of H(f).
Jeff
More information about the Python-list
mailing list