zoukankan      html  css  js  c++  java
  • python内置函数

     内置函数详解:https://docs.python.org/3/library/functions.html?highlight=built#ascii

    abs()  # 取绝对值
    dict() # 把数据转为字典
    help() # 帮助
    min()  # 找出最小值
    max()  # 找出最大值
    setattr()  # 设置属性值
    bool() # 判断True or False(bool(0)、bool(Flase)、bool([]))
    all()  # 可循环的数据集合每个元素bool()均为True;或者空列表也是True
    any()  # 任意一个值是True即返回True
    dir()  # 打印当前程序里的所有变量
    hex()  # 转换为16进制数
    slice()  # 提前定义切片规则
    divmod()  # 传入两个变量a、b,得到a//b结果和余数a%b
    sorted()  # 列表排序sorted(li)等同于li.sort()  用法:sorted(iterable, key)
    
    ascii(2)  # 只能返回ascii码
    enumerate([3,2,13,4])  # 返回列表的索引
    input('dasd')
    oct(10)  # 转八进制
    staticmethod() # 
    bin(10)  # 转二进制
    
    open() # 文件打开
    str()  # 转字符串
    isinstance()
    ord('a')  # 返回97,ascii码中'a'位置
    chr(97)   # 返回'a',输入97位置返回ascii码对应字符
    sum([1,4,5,-1,3,0])   # 计算列表求和
    
    pow(100,2) # 返回x的y次方,10000
    callable()   # 查看函数是否可以调用,还可用于判断变量是否是函数
    format()
    
    vars()  # 打印变量名和对应的值
    locals()  # 打印函数的局部变量(一般在函数内运行)
    globals() # 打印全局变量
    
    repr()  # 显示形式变为字符串
    compile() # 编译代码
    complex() # 将一个数变为复数
    '''
    >>> complex(3,5)
    (3,5j)
    '''
    
    round(1.2344434,2)  # 指定保留几位小数  输出1.23
    # delattr, hasattr, getattr, setattr  # 面向对象中应用
    hash()   # 把一个字符串变为一个数字
    memoryview() # 大数据复制时内存映射
    set()  # 把一个列表变为集合
    '''
    >>> set([12,5,1,7,9])
    {1, 5, 7, 9, 12}
    '''

    几个刁钻古怪的内置方法用法提醒

    1、compile()编译字符串为字节代码

    f = open("print.py")
    data =compile(f.read(),'','exec')  # 参数:source(字符串对象), filename(代码文件名), mode(编译代码种类execevalsingle)
    exec(data)
    
    >>> str = "3 * 4 + 5"
    >>> a = compile(str,'','eval')
    >>> eval(a)
    17
    

    2、items()字典转化数组

    >>> d = {}
    >>> for i in range(10):
    ...        d[i] = i - 50
    ...
    >>> print(d)
    {0: -50, 1: -49, 2: -48, 3: -47, 4: -46, 5: -45, 6: -44, 7: -43, 8: -42, 9: -41}
    >>> d.items()
    dict_items([(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41)])
    >>> sorted(d.items())
    [(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41)]
    >>> sorted(d.items(), key = lambda x:x[1])
    [(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41)]
    >>> sorted(d.items(), key = lambda x:x[1], reverse=True)
    [(9, -41), (8, -42), (7, -43), (6, -44), (5, -45), (4, -46), (3, -47), (2, -48), (1, -49), (0, -50)]
    

    3、字符串转代码

    # eval()  # 字符串转代码(只能处理单行代码)(可以拿到返回值)
    f = "1+3/2"
    eval(f)
    # 输出结果:2.5
    eval('print("hello world")')
    # 输出结果:hello world
    
    # exec() # 字符串转代码(可以解析多行代码)(不能拿到返回值)
    code = "
    if 3>5:
     print('3 bigger than 5')
    else:
     print('dddd')
    
    "
    exec(code)
    # 输出结果:dddd
    
    # eval和exec()返回值验证
    code = '''
    def foo():
        print('run foo')
        return 1234
    foo()
    
    res = eval("1+3+3")
    res2 = exec("1+3+3")
    res3 = exec(code)
    print('res',res,res2,res3)
    # 输出结果:res 7 None None
    

    4、字符串转bytearray

    # bytearray() 将字符串转为bytearray,完成修改后,decode()后,可在原内存地址修改字符串
    
    >>> s = 'abcd路飞'
    >>> s
    'abcd路飞'
    >>> s = s.encode('utf-8')
    >>> s
    b'abcdxe8xb7xafxe9xa3x9e'
    >>> s = bytearray(s)
    >>> s
    bytearray(b'abcdxe8xb7xafxe9xa3x9e')
    >>> s[4]
    232
    >>> s[4]=233
    >>> s
    bytearray(b'abcdxe9xb7xafxe9xa3x9e')
    >>> s.decode()
    'abcd鷯飞'
    >>> id(s)   # 修改内部元素,s指向的内存地址并不会改变
    4352883880
    

     5、map()对序列做映射

    map(lambda x:x*x , [1,2,3,4,5])    # 根据提供的函数对指定序列做映射
    
    >>> list(map(lambda x:x*x , [1,2,3,4,5]))
    [1, 4, 9, 16, 25]
    
    >>>def square(x) :            # 计算平方数
    ...     return x ** 2
    ... 
    >>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
    [1, 4, 9, 16, 25]
    >>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
    [1, 4, 9, 16, 25]
     
    # 提供了两个列表,对相同位置的列表数据进行相加
    >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
    [3, 7, 11, 15, 19]
    

    6、filter()条件过滤

    filter() # 将符合条件的值过滤出来
    # filter(function, iterable)
    >>> list(filter(lambda x: x>3, [1,2,3,4,5]))
    [4, 5]
    
    import math
    def is_sqr(x):
        return math.sqrt(x) % 1 == 0
     
    newlist = filter(is_sqr, range(1, 101))
    print(newlist)
    """
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    """
    

    7、frozenset()不可变集合

    >>> s = {12,3,4,4}
    >>> s.discard(3)  # 集合删除元素,没有也不会报错
    >>> s
    {12,4}
    >>> s = frozenset(s)
    >>> s.   # 已经没有discard方法可以调用
    

    8、zip()两个数组组成元组

    zip()  # 可将两个数组一一对应组成元祖
    
    >>> a = [1,2,3,45,6]
    >>> b = ['a','b','c']
    >>> zip(a)
    <zip object at 0x1034fe408>
    >>> list(zip(a,b))
    [(1, 'a'), (2, 'b'), (3, 'c')]
    

    9、print()带参数的打印

    >>> s = 'hey, my name is alex
    , from shandong'
    >>> print('haifeng','gangsf',sep='<-')
    haifeng<-gangsf
    
    msg = "回到最初的起点"
    f = open("print_tofile","w")
    print(msg,"记忆里青涩的脸",sep="|",end="",file=f)
    print(msg,"已经不忍直视了",sep="|",end="",file=f)
    """
    生成print_tofile文件:回到最初的起点|记忆里青涩的脸回到最初的起点|已经不忍直视了
    """
    

    10、slice()切片

    slice()  # 实现切片对象,主要用在切片操作函数里的参数传递
    # 例子:slice('start', 'stop', 'step')  # 起始位置、结束位置、间距
    
    a = range(20)
    pattern = slice(3, 8, 2) # 3到8,间隔两个数
    for i in a[pattern]:  # 等于a[3:8:2]
        print(i)

    11、reduce()对参数序列中元素进行累积

      reduce() 函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。

    reduce() 函数语法:
    reduce(function, iterable[, initializer])
    
    参数
        function -- 函数,有两个参数
        iterable -- 可迭代对象
        initializer -- 可选,初始参数
    

       返回值:函数计算结果

    >>>def add(x, y) :            # 两数相加
    ...     return x + y
    ... 
    >>> reduce(add, [1,2,3,4,5])   # 计算列表和:1+2+3+4+5
    15
    >>> reduce(lambda x, y: x+y, [1,2,3,4,5])  # 使用 lambda 匿名函数
    15
    
  • 相关阅读:
    Populating Next Right Pointers in Each Node II
    Populating Next Right Pointers in Each Node
    Construct Binary Tree from Preorder and Inorder Traversal
    Construct Binary Tree from Inorder and Postorder Traversal
    Path Sum
    Symmetric Tree
    Solve Tree Problems Recursively
    632. Smallest Range(priority_queue)
    609. Find Duplicate File in System
    poj3159最短路spfa+邻接表
  • 原文地址:https://www.cnblogs.com/xiugeng/p/8594882.html
Copyright © 2011-2022 走看看