Lambda Expression

|--Lambda Expression
#f(x) = x^2

    def f(x):
        return x * x

    print(f(5))

    f = lambda x: x*x

    print(f(5))

    def g(x, y):
        return x * y

    g = lambda x,y: x+y

    print(g(4, 5))

eg:

    countries = []
        file = open("countries_zh.csv", "r")
        for line in file:
            line = line.strip()
            arr = line.split(",")
            name = arr[1]
            capt = arr[3]
            popu = int(arr[4])
            countries.append( (name, capt, popu) )
        countries.sort(key= lambda country: country[2])
        for country in countries:
            print(country)


|--用于复合函数(一个函数嵌套一个函数)

    f(x) = ax^2 + bx + c

    def quadratic(a, b, c):
        return lambda x: a*x*x + b*x + c

    f = quadratic(1, -1, 2)
    print(f(5))

    print(quadratic(1, -1, 2)(5))
posted @ 2019-07-14 20:27  电院院长  阅读(209)  评论(0编辑  收藏  举报