【python基礎】六、python之匿名函數

匿名函數

作用:簡化函數的定義

def func(a, b):
    c = a + b
    print(c)
    return c
  • 格式:

    • 關鍵字 lambda

    lambda 參數1, 參數2: 函數體

  • 如何調用:

    s = lambda

s = lambda a, b: a + b
print(s)    # s 是個函數
  • 如何判斷 有無返回呢

    只要運算 就返回

匿名函數 作爲 參數出現

def func(x, y, f):
    print(x,y)
    f(x,y)
    
func(1, 2, lambda a, b: a + b)

匿名函數 與 內置函數

lt1 = [1, 2, 3, 4, 9]
print(max(lt1))  # max可以傳入 列表

lt2 = [{'a': 10, 'b': 11}, {'a': 20, 'b': 21}, {'a': 30, 'b': 31}, {'a': 40, 'b': 41}, ]
# print(max(lt2))
# max(iterable, *[, default=obj, key=func]) -> value
m = max(lt2, key=lambda x: x['a'])
print(m)

上面代碼,max()可以傳入列表,求其最大值
但是傳入的 列表包含 字典,如何求 字典 key=‘a’,的最大值呢
因此 lambda 用在傳入參數爲func 的位置

其他 內置函數
  • map()

    map(func, *iterables) --> map object
    Make an iterator that computes the function using arguments from
    each of the iterables.
    Stops when the shortest iterable is exhausted.

  • reduce()
  • filter()
  • sorted()
lt1 = [1, 2, 3, 4, 9]
res = map(lambda x: x * 2, lt1)

print(res)
print(list(res))


map(lambda x: x if x % 2 == 0 else x + 1, lt1)

from functools import reduce
reduce(lambda x, y: x + y, lt1)

filter(lambda x: x > 3, lt1)

filter(lambda x:x['xx'], dict)


sorted(dict, key=lambda x:x['xx'])

遞歸函數

函數自己 調用自己

  • 特點:
    1. 調用 自身
    2. 設定終點,判斷結束
    3. 設定起點,傳入參數
def sum(n):
    if n == 0:
        return 0
    else:
        return n + sum(n - 1)

re = sum(10)

print(re)

def p(n):
    if n == 0:
        print(n)
    else:
        print(n)
        p(n-1)

p(5)

在b站學習中,學習鏈接

個人主頁

歡迎 批評 指正

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章