Issue 7402: Improve reduce() example in the python idioms how-to.

This commit is contained in:
Raymond Hettinger 2010-10-31 22:01:57 +00:00
parent 30bf6e836e
commit c6b6b5bf5a
1 changed files with 14 additions and 16 deletions

View File

@ -244,24 +244,22 @@ Compare::
More useful functions in :mod:`os.path`: :func:`basename`, :func:`dirname` and More useful functions in :mod:`os.path`: :func:`basename`, :func:`dirname` and
:func:`splitext`. :func:`splitext`.
There are also many useful built-in functions people seem not to be aware of for There are also many useful built-in functions people seem not to be aware of
some reason: :func:`min` and :func:`max` can find the minimum/maximum of any for some reason: :func:`min` and :func:`max` can find the minimum/maximum of
sequence with comparable semantics, for example, yet many people write their own any sequence with comparable semantics, for example, yet many people write
:func:`max`/:func:`min`. Another highly useful function is their own :func:`max`/:func:`min`. Another highly useful function is
:func:`functools.reduce`. A classical use of :func:`reduce` is something like :func:`functools.reduce` which can be used to repeatly apply a binary
:: operation to a sequence, reducing it to a single value. For example, compute
a factorial with a series of multiply operations::
import sys, operator, functools >>> n = 4
nums = list(map(float, sys.argv[1:])) >>> import operator, functools
print(functools.reduce(operator.add, nums) / len(nums)) >>> functools.reduce(operator.mul, range(1, n+1))
24
This cute little script prints the average of all numbers given on the command When it comes to parsing numbers, note that :func:`float`, :func:`int` and
line. The :func:`reduce` adds up all the numbers, and the rest is just some :func:`long` all accept string arguments and will reject ill-formed strings
pre- and postprocessing. by raising an :exc:`ValueError`.
On the same note, note that :func:`float` and :func:`int` accept arguments of
type string, and so are suited to parsing --- assuming you are ready to deal
with the :exc:`ValueError` they raise.
Using Backslash to Continue Statements Using Backslash to Continue Statements