• 技术文章 >Python技术 >Python基础教程

    python中lambda的用法

    yfyf2020-05-12 17:48:58转载2781
    对于一个函数,只有一句话表示,那么就可以用lambda表达式表示,如:

    def f(x):
    return x * x
    print(f(5))
    out: 25

    可以写为:

    f = lambda x: x*x # 冒号左边为输入,右边是返回值,f是函数名
    print(f(5))
    out: 25

    对于多个形式参数:

    g = lambda x,y: x+y # 冒号左边为输入,右边是返回值,f是函数名
    print(g(4,5))
    out: 9

    lambda用到比较多的地方是排序,如:

    def get_four(my):
    return my[2]
    tuple_my = []
    file = open("file.csv", "r")
    for line in file:
    Line = line.strip()
    arr = line.split(",")
    one = arr[1]
    three = arr[3]
    four = int(arr[4])
    tuple_my.append( (one, three, four) )
    tuple_my.sort(key=get_four)
    for my in tuple_my:
    print(my)

    可以写为:

    get_four = lambda my: my[2]
    tuple_my = []
    file = open("file.csv", "r")
    for line in file:
    Line = line.strip()
    arr = line.split(",")
    one = arr[1]
    three = arr[3]
    four = int(arr[4])
    tuple_my.append( (one, three, four) )
    tuple_my.sort(key=get_four)
    for my in tuple_my:
    print(my)
    tuple_my = []
    file = open("file.csv", "r")
    for line in file:
    Line = line.strip()
    arr = line.split(",")
    one = arr[1]
    three = arr[3]
    four = int(arr[4])
    tuple_my.append( (one, three, four) )
    tuple_my.sort(key=lambda my: my[2])
    for my in tuple_my:
    print(my)

    lambda也经常用在符合函数下,如:

    def quadratic(a, b, c):
    return lambda x: a*x*x*x + b*x*x + c*x
    f = quadratic(3, -2, 4)
    print(f(5))
    345
    def quadratic(a, b, c):
    return lambda x: a*x*x*x + b*x*x + c*x
    print(quadratic(3, -2, 4)(5))
    345
    专题推荐:python lambda
    上一篇:python中的赋值方法 下一篇:在vscode中编写Python的详细步骤

    相关文章推荐

    • Python lambda表达式及用法• Python中reduce函数和lambda表达式的学习• Python中lambda表达式的优缺点及使用场景

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网