在线不卡日本ⅴ一区v二区_精品一区二区中文字幕_天堂v在线视频_亚洲五月天婷婷中文网站

  • <menu id="lky3g"></menu>
  • <style id="lky3g"></style>
    <pre id="lky3g"><tt id="lky3g"></tt></pre>

    Python 大家都該知道的高階函數(shù)

    函數(shù)式編程現(xiàn)在逐漸被廣大開發(fā)群體接受,越來越多的開發(fā)者們開始使用這種優(yōu)雅的開發(fā)模式,而我們使用函數(shù)式編程最主要的是需要清楚:

    • 什么是高階函數(shù)(Higher-order Functions)?
    • Python 中高階函數(shù)有哪些?要怎么用?

    高階函數(shù)概念

    在函數(shù)式編程中,我們可以將函數(shù)當(dāng)作變量一樣自由使用。一個函數(shù)接收另一個函數(shù)作為參數(shù),這種函數(shù)稱之為高階函數(shù)。

    舉個例子

    def high_func(f, arr): return [f(x) for x in arr]

    上面的例子中, high_func 就是一個高階函數(shù)。其中第一個參數(shù) f 是一個函數(shù),第二個參數(shù) arr 是一個數(shù)組,返回的值是數(shù)組中的所有的值在經(jīng)過 f 函數(shù)計算后得到的一個列表。例如:

    from math import factorialdef high_func(f, arr): return [f(x) for x in arr]def square(n): return n ** 2# 使用python自帶數(shù)學(xué)函數(shù)print(high_func(factorial, list(range(10))))# print out: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]# 使用自定義函數(shù)print(high_func(square, list(range(10))))# print out: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

    Python 常用高階函數(shù)

    如同 java、scala 等語言,我們很多常用的高階函數(shù)基本都一致。在開發(fā)中我們經(jīng)常使用的最基本的高階函數(shù)其實就幾個,而我們也可以基于這些函數(shù)去進(jìn)行適當(dāng)?shù)臄U展,那么下面開始介紹幾種常用的高階函數(shù)。

    map

    Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.

    根據(jù)提供的函數(shù)對指定序列做映射, 并返回映射后的序列,定義:

    map(func, *iterables) –> map object

    • function # 序列中的每個元素需要執(zhí)行的操作, 可以是匿名函數(shù)
    • *iterables # 一個或多個序列

    正如前面所舉的例子 high_func 函數(shù), map 函數(shù)是 high_func 函數(shù)高階版,可以傳入一個函數(shù)和多個序列。

    from math import factorialdef square(n): return n ** 2# 使用python自帶數(shù)學(xué)函數(shù)facMap = map(factorial, list(range(10)))print(list(facMap))# print out: [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]# 使用自定義函數(shù)squareMap = map(square, list(range(10)))print(list(squareMap))# print out: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

    可以看到輸出了同樣的結(jié)果,只是與 python2.X 不同的是, python3.X 中返回 map 類 ,而前者直接返回一個列表。

    我們使用匿名函數(shù),也可以傳入多個序列,如下圖

    # 使用匿名函數(shù)lamMap = map(lambda x: x * 2, list(range(10)))print(list(lamMap))# print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]# 傳入多個序列mutiMap = map(lambda x, y: x+y, list(range(10)), list(range(11, 15)))print(list(mutiMap))# print out: [11, 13, 15, 17]

    reduce

    Apply a function of two arguments cumulatively to the items of a sequence,from left to right, so as to reduce the sequence to a single value.

    大致上來講, reduce 函數(shù)需要傳入一個有兩個參數(shù)的函數(shù),然后用這個函數(shù)從左至右順序遍歷序列并生成結(jié)果,定義如下:

    reduce(function, sequence[, initial]) -> value

    • function # 函數(shù), 序列中的每個元素需要執(zhí)行的操作, 可以是匿名函數(shù)
    • sequence # 需要執(zhí)行操作的程序列
    • initial # 可選,初始參數(shù)

    最后返回函數(shù)的計算結(jié)果, 和初始參數(shù)類型相同

    簡單舉個例子:

    # 注意,現(xiàn)在 reduce() 函數(shù)已經(jīng)放入到functools包中。from functools import reduceresult = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])print(result)# print out 15

    我們可以看到,序列 [1, 2, 3, 4, 5] 通過匿名函數(shù)進(jìn)行了累加。

    設(shè)定初始值:

    # 設(shè)定初始參數(shù):s = reduce(lambda x, y: x + y, [‘1’, ‘2’, ‘3’, ‘4’, ‘5’], “數(shù)字 = “)print(s)# print out: 數(shù)字 = 12345

    需要注意的是:序列數(shù)據(jù)類型需要和初始參數(shù)一致。

    filter

    Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.

    filter() 函數(shù)用來過濾序列中不符合條件的值,返回一個迭代器,該迭代器生成那些函數(shù)(項)為 true 的 iterable 項。如果函數(shù)為 None,則返回為 true 的項。定義如下:

    filter(function or None, iterable) –> filter object

    • function or None # 過濾操作執(zhí)行的函數(shù)
    • iterable # 需要過濾的序列

    舉個例子:

    def boy(n): if n % 2 == 0: return True return False# 自定義函數(shù)filterList = filter(boy, list(range(20)))print(list(filterList))# print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]# 自定義函數(shù)filterList2 = filter(lambda n: n % 2 == 0, list(range(20)))print(list(filterList2))# print out: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

    上面我們可以看到,列表中不能被 2 整除的數(shù)據(jù)都被排除了。

    sorted

    Return a new list containing all items from the iterable in ascending order.

    A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.

    sorted 函數(shù)默認(rèn)將序列升序排列后返回一個新的新的 list,還可以自定義鍵函數(shù)來進(jìn)行排序,也可以設(shè)置 reverse 參數(shù)確定是升序還是降序,如果 reverse = True 則為降序。函數(shù)定義如下:

    def sorted(iterable: Iterable[_T], *, key: Optional[Callable[[_T], Any]] = …, reverse: bool = …) -> List[_T]: …

    • iterable # 序列
    • key # 可以用來計算的排序函數(shù)。
    • reverse # 排序規(guī)則,reverse = True 降序,reverse = False 升序(默認(rèn))。

    舉個簡單的例子:

    list01 = [5, -1, 3, 6, -7, 8, -11, 2]list02 = [‘apple’, ‘pig’, ‘monkey’, ‘money’]print(sorted(list01))# print out: [-11, -7, -1, 2, 3, 5, 6, 8]print(sorted(list01, key=abs))# print out: [-1, 2, 3, 5, 6, -7, 8, -11]# 默認(rèn)升序print(sorted(list02))# print out: [‘apple’, ‘money’, ‘monkey’, ‘pig’]# 降序print(sorted(list02, reverse=True))# print out: [‘pig’, ‘monkey’, ‘money’, ‘apple’]# 匿名函數(shù)排序print(sorted(list02, key=lambda x: len(x), reverse=True))# print out: [‘monkey’, ‘apple’, ‘money’, ‘pig’]

    鄭重聲明:本文內(nèi)容及圖片均整理自互聯(lián)網(wǎng),不代表本站立場,版權(quán)歸原作者所有,如有侵權(quán)請聯(lián)系管理員(admin#wlmqw.com)刪除。
    上一篇 2022年6月27日 22:36
    下一篇 2022年6月27日 22:36

    相關(guān)推薦

    聯(lián)系我們

    聯(lián)系郵箱:admin#wlmqw.com
    工作時間:周一至周五,10:30-18:30,節(jié)假日休息