]> granicus.if.org Git - python/commitdiff
Issue #18652: Add an itertools recipe for first_true()
authorRaymond Hettinger <python@rcn.com>
Wed, 2 Apr 2014 10:16:42 +0000 (03:16 -0700)
committerRaymond Hettinger <python@rcn.com>
Wed, 2 Apr 2014 10:16:42 +0000 (03:16 -0700)
Doc/library/itertools.rst
Lib/test/test_itertools.py

index 5d3e50a86ddae9cafd9fe67a46efbdd2a918d0c8..f489535c5361808123314e90002a546a0b8c4d24 100644 (file)
@@ -784,6 +784,19 @@ which incur interpreter overhead.
        except exception:
            pass
 
+   def first_true(iterable, default=False, pred=None):
+       """Returns the first true value in the iterable.
+
+       If no true value is found, returns *default*
+
+       If *pred* is not None, returns the first item
+       for which pred(item) is true.
+
+       """
+       # first_true([a,b,c], x) --> a or b or c or x
+       # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
+       return next(filter(pred, iterable), default)
+
    def random_product(*args, repeat=1):
        "Random selection from itertools.product(*args, **kwds)"
        pools = [tuple(pool) for pool in args] * repeat
index 21f1bdeb82c4d14b4fee6f8a011948d195e32bb8..3a580ad9b2df2235d42e966aedaad1dfbac3e6d1 100644 (file)
@@ -1998,6 +1998,19 @@ Samuele
 ...     # unique_justseen('ABBCcAD', str.lower) --> A B C A D
 ...     return map(next, map(itemgetter(1), groupby(iterable, key)))
 
+>>> def first_true(iterable, default=False, pred=None):
+...     '''Returns the first true value in the iterable.
+...
+...     If no true value is found, returns *default*
+...
+...     If *pred* is not None, returns the first item
+...     for which pred(item) is true.
+...
+...     '''
+...     # first_true([a,b,c], x) --> a or b or c or x
+...     # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
+...     return next(filter(pred, iterable), default)
+
 This is not part of the examples but it tests to make sure the definitions
 perform as purported.
 
@@ -2075,6 +2088,9 @@ True
 >>> list(unique_justseen('ABBCcAD', str.lower))
 ['A', 'B', 'C', 'A', 'D']
 
+>>> first_true('ABC0DEF1', '9', str.isdigit)
+'0'
+
 """
 
 __test__ = {'libreftest' : libreftest}