国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python中的map、reduce和filter淺析

2020-02-23 05:19:45
字體:
來源:轉載
供稿:網(wǎng)友

1、先看看什么是 iterable 對象

以內(nèi)置的max函數(shù)為例子,查看其doc:
代碼如下:
>>> print max.__doc__
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.
在max函數(shù)的第一種形式中,其第一個參數(shù)是一個 iterable 對象,既然這樣,那么哪些是 iterable 對象呢?
代碼如下:
>>> max('abcx')
>>> 'x'
>>> max('1234')
>>> '4'
>>> max((1,2,3))
>>> 3
>>> max([1,2,4])
>>> 4
我們可以使用yield生成一個iterable 對象(也有其他的方式):
代碼如下:
def my_range(start,end):
    ''' '''
    while start <= end:
        yield start
        start += 1
執(zhí)行下面的代碼:
代碼如下:
for num in my_range(1, 4):
    print num
print max(my_range(1, 4))
將輸出:
代碼如下:
1
2
3
4
4


2、map

在http://docs.python.org/2/library/functions.html#map中如此介紹map函數(shù):
代碼如下:
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函數(shù)使用自定義的function處理iterable中的每一個元素,將所有的處理結果以list的形式返回。例如:
代碼如下:
def func(x):
    ''' '''
    return x*x

print map(func, [1,2,4,8])
print map(func, my_range(1, 4))
運行結果是:
代碼如下:
[1, 4, 16, 64]
[1, 4, 9, 16]
也可以通過列表推導來實現(xiàn):
代碼如下:
print [x*x for x in [1,2,4,8]]

3、reduce

在http://docs.python.org/2/library/functions.html#reduce中如下介紹reduce函數(shù):
代碼如下:
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.

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 南涧| 会昌县| 凤冈县| 桂林市| 饶河县| 盘山县| 通城县| 青阳县| 遵化市| 新宁县| 宁津县| 曲阳县| 宁陕县| 黄大仙区| 德钦县| 连云港市| 宾阳县| 元朗区| 道真| 涿鹿县| 特克斯县| 深州市| 伊吾县| 宜阳县| 吉水县| 柘城县| 丰镇市| 淮南市| 阜新| 太原市| 马山县| 南通市| 赫章县| 姜堰市| 抚松县| 乐陵市| 安泽县| 固阳县| 汕尾市| 会昌县| 泽库县|