zoukankan      html  css  js  c++  java
  • 函数function

    Function

    function namespace mechanism

     When you call a function, it
    gets a private namespace where its local variables are created. When the function reaches a return statement,
    the local variables are destroyed and the value is returned to the caller. A later call to the same function
    creates a new private namespace and a fresh set of local variables.

    Use def statement to define function  

     匿名函数

    lamba x:x*2+1

    g=lamba x:x*2+1

    g(2)

    g=lambda x,y:x*y+1


    built-in function

    filter() 过滤器

    list(filter(lambda x:x%2,[1,2,3,4,5,6,7,8,9]))

    divmod函数

    View Code

    divmod返回一个tuple ,(x//y,x%y)

    enumerate(iterable)

    返回的事一个迭代器,包含他的值和索引

    View Code
    View Code

    frozenset()创建一个被冰冻的集合,不可删除,不可添加

    View Code

    globals()  locals()  返回字典形式的,当前范围内的全局变量/局部变量

    View Code

    isinstance() 判断类型

    type(s)
    <class 'frozenset'>
    >>> isinstance(s,frozenset)
    True

    zip()  返回一个元组,参数为两个可迭代的对象。

    View Code

    max() min()   返回最大值,最小值,参数可以是一个可迭代对象或者多个普通参数

    匿名函数:

    格式:lambda 参数,参数: 函数表达式

    应用于一些很简单的函数,自带return 效果

    map() ,映射函数

    map()函数接收两个参数,一个是函数,一个是Iterablemap将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。

    比如将一个列表的每个元素都平方得到一个新的序列,可以用map方法

    View Code
    View Code

    reduce()函数

    from functools import reduce

    使用reduce,必须要导入from functools import reduce     reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:

    reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

    View Code
    View Code

    filter函数
    和map类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
    View Code
  • 相关阅读:
    Linux之硬件资源管理
    Linux之vi 文本编辑命令
    [2]窗口程序的创建
    [1]cs辅助项目分解
    1.3 Windows操作系统
    (PYG)学习去除软件自效验
    CSUST 4006-你真的会树套树套树吗?(贪心|dp)
    CSUST 4003-你真的会泡面吗?(优先队列模拟)
    2020牛客暑期多校第八场I-Interesting Computer Game(离散化+并查集)
    2020牛客暑期多校K-Kabaleo Lite(贪心)
  • 原文地址:https://www.cnblogs.com/yuyang26/p/6954110.html
Copyright © 2011-2022 走看看