Hi,

On Fri, Apr 3, 2009 at 17:45, Sebastian Rittau
<srit...@jroger.in-berlin.de> wrote:
> I am missing a simple way to retrieve the "first" element of any
> iterable in python that matches a certain condition anyway. Something
> like this:
>
>  def first(iter, cb):
>      for el in iter:
>          if cb(el):
>              return el
>      raise IndexError()
>
> Or (shorter, but potentially slower):
>
>  def first(iter, cb):
>      return [el for el in iter if cb(el)][0]
>
> To be used like this:
>
>  my_el = first(my_set, lambda el: el == "foobar")
>
> This is something I need from time to time and this also seems to solve
> your problem.

def first(iter, cb):
    return itertools.ifilter(cb, iter).next()

-- 
Amaury Forgeot d'Arc
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to