Can this be written more concisely in a functional style
Alexander Schmolck
a.schmolck at gmx.net
Tue Nov 18 12:48:34 EST 2003
tweedgeezer at hotmail.com (Jeremy Fincher) writes:
> jcb at iteris.com (MetalOne) wrote in message news:<92c59a2c.0311172340.544faac6 at posting.google.com>...
> > Maybe my post was not clear.
> > I want a means to test if there exists an element in the list that
> > satisfies a predicate.
>
> Sure there is. The code that you showed was an excellent way to do
> so.
>
> > Actually, when I word it that way, I guess what I want is PEP 289,
> > universal and existential qualifiers.
> >
> > I guess I'll have to wait.
>
> Why? Why not just stuff the code you wrote into an appropriately
> named function and use that?
>
> Anyway, here are more efficient implementations:
>
> def any(p, seq):
> """Returns true if any element in seq satisfies predicate p."""
> for elt in itertools.ifilter(p, seq):
> return True
> else:
> return False
Another alternative (also works for python2.2, but is likely to be slower):
def some(predicate, *seqs):
iterables = map(iter, seqs)
try:
while 1:
boo = predicate(*[iterable.next() for iterable in iterables])
if boo: return boo
except StopIteration: return False
'as
More information about the Python-list
mailing list