• python 学习笔记 五


    函数

    下面看一个打印斐波那契数列的函数:

    def fabs(n):
        a, b = 0, 1
        while a < n:
            print a
            a, b = b, a+b

    从这个例子可以看除Python函数的结构.

    记录函数

    如果想要给函数写文档, 可以加如注释(#开头), 另一种方式是直接写上字符串, 比如在def语句后面, 在函数定义下面的字符串会作为函数的一部分进行存储, 这称为文档字符串.

    例如:

    def squart(x):
        'Calculates the squart of the number x.'
        return x*x

    可以这样访问文档字符串:

    >>> sqare.__doc__

    关键字参数和默认值

    定义函数时, 可以为参数设置默认值, 这样调用函数时可以不提供参数:

    >>>  def hello(greeting='Hello', name='world'): print'%s, %s' % (greeting, name)

    >>> hello()

    Hello, world

    此外, 调用函数时, 可以为实参指定形参关键字, 这样可以忽略参数顺序的影响, 例:

    >>> hello(name='bob', greeting='Hi, ')

    Hi, bob

    收集参数

    在参数前面加上*号可以将所有值放入同一个元组中, 可以说是将这些值收集起来, 然后使用.

    能处理关键字的收集操作: **, 将参数收集为字典.

    反转过程

    有这样一个函数:

    def add(x, y): return x + y

    有这样一个元组:

    params = (1, 2)

    这样调用函数:

    add(*params)

    函数式编程

      1.map(function, sequence)

    对每一个序列元素调用函数, 返回包含所有函数返回值的列表

    >>> def cube(x): return x*x*x
    ...
    >>> map(cube, range(1, 11))
    [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

      2.filter(function, sequence)

    filter函数可以基于一个返回布尔值的函数对元素进行过滤, 它返回包含一些元素的序列, 这些元素在funcrtion(item)返回True. 如果序列是字符串或元组, 结果将是相同的类型, 否则, 结果总是一个列表.例如:

    >>> def f(x): return x % 2 != 0 and x % 3 != 0
    ...
    >>> filter(f, range(2, 25))
    [5, 7, 11, 13, 17, 19, 23]
      

       3.lambda

    匿名函数可以用lambda关键字创建. Lambda可以用于需要函数对象的地方:

    >>> fileter[lambda x: x % 2 != 0 and x % 3 != 0, seq]

    注: map和filter在目前版本Python中并不是特别有用, 可以使用列表推导式代替, 例如:

    >>> [x for x in range(1, 25) if x % 2 != 0 and x % 3 != 0]

  • 相关阅读:
    三层架构
    【Leetcode】Linked List Cycle II
    [Angular] @ContentChild with Directive ref
    [PostgreSQL] Use Foreign Keys to Ensure Data Integrity in Postgres
    [PostgreSQL] Ensure Uniqueness in Postgres
    [RxJS] Hot Observable, by .share()
    [RxJS] Implement pause and resume feature correctly through RxJS
    [RxJS] Replace zip with combineLatest when combining sources of data
    [RxJS] Use takeUntil instead of manually unsubscribing from Observables
    [RxJS] Convert RxJS Subjects to Observables
  • 原文地址:https://www.cnblogs.com/ezhengnan/p/3746466.html
Copyright © 2020-2023  润新知