[Python-checkins] cpython (merge 3.4 -> default): merge

raymond.hettinger python-checkins at python.org
Wed Apr 2 12:17:43 CEST 2014


http://hg.python.org/cpython/rev/6154c7f2bf75
changeset:   90107:6154c7f2bf75
parent:      90105:2a41d3f81b46
parent:      90106:3e2354dde892
user:        Raymond Hettinger <python at rcn.com>
date:        Wed Apr 02 03:17:33 2014 -0700
summary:
  merge

files:
  Doc/library/itertools.rst  |  13 +++++++++++++
  Lib/test/test_itertools.py |  16 ++++++++++++++++
  2 files changed, 29 insertions(+), 0 deletions(-)


diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -784,6 +784,19 @@
        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
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -1998,6 +1998,19 @@
 ...     # 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 @@
 >>> list(unique_justseen('ABBCcAD', str.lower))
 ['A', 'B', 'C', 'A', 'D']
 
+>>> first_true('ABC0DEF1', '9', str.isdigit)
+'0'
+
 """
 
 __test__ = {'libreftest' : libreftest}

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list