zoukankan      html  css  js  c++  java
  • Python: Lambda Functions

    1. 作用

    快速创建匿名单行最小函数,对数据进行简单处理, 常常与 map(), reduce(), filter() 联合使用。

    2. 与一般函数的不同

    >>> def f (x): return x**2
    ...
    >>> print f(8)
    64
    >>>
    >>> g = lambda x: x**2 # 匿名函数默认冒号前面为参数(多个参数用逗号分开), return 冒号后面的表达式
    >>>
    >>> print g(8)
    64

    3. 与一般函数嵌套使用

    与一般函数嵌套,可以产生多个功能类似的的函数。

    >>> def make_incrementor (n): return lambda x: x + n
    >>>
    >>> f = make_incrementor(2)
    >>> g = make_incrementor(6)
    >>>
    >>> print f(42), g(42)
    44 48
    >>>
    >>> print make_incrementor(22)(33)
    55

    4. 在 sequence 中的使用

    filter(function or None, sequence) -> list, tuple, or string

    map(function, sequence[, sequence, ...]) -> list

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

    >>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
    >>>
    >>> print filter(lambda x: x % 3 == 0, foo)
    [18, 9, 24, 12, 27]
    >>>
    >>> print map(lambda x: x * 2 + 10, foo)
    [14, 46, 28, 54, 44, 58, 26, 34, 64]
    >>>
    >>> print reduce(lambda x, y: x + y, foo) # return (((((a+b)+c)+d)+e)+f) equal to sum()
    139

    5. 两个例子

    a) 求素数

    >>> nums = range(2, 50)
    >>> for i in range(2, 8):
    ... nums = filter(lambda x: x == i or x % i, nums)
    ...
    >>> print nums
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

    注释: "Leave the element in the list if it is equal to i, or if it leaves a non-zero remainder when divided by i. Otherwise remove it from the list." 从 2 到 7 循环,每次把倍数移除。

    b) 求单词长度

    >>> sentence = 'It is raining cats and dogs'
    >>> words = sentence.split()
    >>> print words
    ['It', 'is', 'raining', 'cats', 'and', 'dogs']
    >>>
    >>> lengths = map(lambda word: len(word), words)
    >>> print lengths
    [2, 2, 7, 4, 3, 4]


    参考资料:

    http://www.secnetix.de/olli/Python/lambda_functions.hawk

  • 相关阅读:
    mojo 接口示例
    MojoliciousLite: 实时的web框架 概述
    接口返回json
    centos 6.7 perl 版本 This is perl 5, version 22 安装DBI DBD
    centos 6.7 perl 5.22 安装DBD 需要使用老的perl版本
    商业智能改变汽车行业
    商业智能改变汽车行业
    读MBA经历回顾(上)目的决定手段——北漂18年(48)
    perl 升级到5.20版本
    Group Commit of Binary Log
  • 原文地址:https://www.cnblogs.com/daniel-D/p/3175426.html
Copyright © 2011-2022 走看看