## map函数：

map(function, iterable, ...)

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

## map函数示例：

>>> map(lambda x : x*2, [1, 2, 3, 4, 5])
[2, 4, 6, 8, 10]

>>> map(lambda x, y : x+y, [1, 3, 5], [2, 4, 6])
[3, 7, 11]

>>> map(lambda x, y : str(x)+str(y), ['a', 'e', 'i'], ['o', 'u'])
['ao', 'eu', 'iNone']

function为None：

>>> map(None, [1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]

function为None，且传递多个iterable对象：

>>> map(None, [1, 3, 5], [2, 4, 6])
[(1, 2), (3, 4), (5, 6)]

## reduce函数：

reduce(function, iterable[, initializer])

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned. Roughly equivalent to:

def reduce(function, iterable, initializer=None):
it = iter(iterable)
if initializer is None:
try:
initializer = next(it)
except StopIteration:
raise TypeError('reduce() of empty sequence with no initial value')
accum_value = initializer
for x in it:
accum_value = function(accum_value, x)
return accum_value

## reduce函数示例：

>>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
15

>>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5], 6)
21

>>> reduce(lambda x, y: x+y, [], 6)
6

>>> reduce(lambda x, y: x+y, [1])
1

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: reduce() of empty sequence with no initial value

Pingbacks已关闭。