zoukankan      html  css  js  c++  java
  • python 中的内置高级函数

    1.map(function,iterable)

    map是把迭代对象依次进行函数运算,并返回。

    例子:

    map返回的十分map对象,需要list()函数转化。

    2.exec()函数

     执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码。

    Execute the given source in the context of globals and locals.  在全局变量和局部变量上下文中执行给定的源。
    
    The source may be a string representing one or more Python statements or a code object as returned by compile(). 
    The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals.
    全局变量必须是一个字典类型,局部变量可以是任何映射
    If only globals is given, locals defaults to it.
    如果仅仅给订全局变量,局部变量也默认是它。
    # 执行单行语句
    exec('print("Hello World")')
    # 执行多行语句
    exec("""
    for i in range(10):
        print(i,end=",")
    """)
    
    运行结果
    Hello World
    0,1,2,3,4,5,6,7,8,9,
    

     

    x = 10  # global
    expr = """
    z = 30 
    sum = x + y + z
    print(sum)
    print("x= ",x)
    print("y= ",y)
    print("z= ",z)
    """
    def func():
        y = 20 #局部变量
        exec(expr)
        exec(expr, {'x': 1, 'y': 2})
        exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})
    
    # python寻找变量值的顺寻,LEGB
    # L->Local 局部变量
    # E->Enclosing function locals 函数内空间变量
    # G->global 全局变量
    # B-> bulltlins
    # 局部变量———闭包空间———全局变量———内建模块
    func()
    

     结果是:

    60
    x=  10 ,y=  20,z=  30
    33
    x=  1 ,y=  2, z=  30
    34
    x=  1 ,y=  3 ,z=  30

    python 中寻找变量顺序:

    LEGB

    L-Local

    E->enclose function local

    G->global

    B->bultins

    局部变量->函数体内变量-》全局变量-》内置函数

    3.zip()函数

    zip() is a built-in Python function that gives us an iterator of tuples

    for i in zip([1,2,3],['a','b','c']):
            print(i)

    结果:
    (1,'a')
    (2,'b')
    (3,'c')

     

    zip将可迭代对象作为参数,将对象中对应的元素打包组成一个个元组,然后返回这些元组组成的列表。

    而zip(*c)则是将原来的组成的元组还原成原来的对象。

    4.repr()函数

    repr() 函数将对象转化为供解释器读取的形式。返回一个对象的 string 格式。

     看以看出来当输入的是”123“,则str()函数输出的是123,而repr输出的是”123“.

    str()不保留原来的类型,而repr则保留数据类型。

  • 相关阅读:
    GitLab CI/CD的官译【原】
    Gearman介绍、原理分析、实践改进
    Golang逃逸分析
    Go 程序是怎样跑起来的
    分布式系统的常见玩法
    开发更高可用、高质量的服务的一些建议
    理解 Kubernetes 的亲和性调度
    服务发现对比:Zookeeper vs etcd vs Consul
    探索etcd,Zookeeper和Consul一致键值数据存储的性能
    CentOS 7 安装无线驱动
  • 原文地址:https://www.cnblogs.com/hamish26/p/11041305.html
Copyright © 2011-2022 走看看