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则保留数据类型。

  • 相关阅读:
    sicp-py
    Ubuntu下找不到ttyUSB*问题解决
    Mysql基本命令及数据库存储位置
    open-vm-tools与VMware Tools
    64位ubuntu安装交叉编译工具链,显示找不到命令
    VMware Tools 继续运行脚本未能在虚拟机中成功运行。
    VMware Workstation 14安装VMware Tools
    VMware Workstation14 安装Ubuntu18.04
    Linux安装Sqlite
    mysql中文乱码
  • 原文地址:https://www.cnblogs.com/hamish26/p/11041305.html
Copyright © 2011-2022 走看看