zoukankan      html  css  js  c++  java
  • 拓展:内置函数

    拓展:内置函数

     案例:
    返回数字的绝对值abs()
    原始写法: 
    def a(x):
        if x < 0:
            return(-x)
        return(x)
     
    #n = a(10)return(x)n = a(-10)return(-x)
    n = a(-10)
    print(n)
     直接调用abs()内置函数 
    >>> abs(10)
    10
    >>> abs(-10)
    10
    >>> abs(-32)
    32
    >>> 
     
    最大值最小值 
    >>> l = [1,2,3,45,5,7,8,324,23,4556,32,1234]
    >>> max(l)
    4556
    >>> min(l)
    1
    >>> 

    len()取序列的长度(可迭代次数)
     >>> len(l)
    12

    divmod() 取商,模运算,返回一个元组,
    divmod(...)
        divmod(x, y) -> (div, mod)
        
        Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.
     
    >>> divmod(5,2)
    (2, 1)
    >>> divmod(2,5)
    (0, 2)
    >>> 
     
     pow()有2个参数和一个可变参数,当pow()有两个参数时返回(第一个参数)的(第二个参数)次幂,如果有第三个参数,则取第三个参数的余数(比较拗口)
    pow(...)
        pow(x, y[, z]) -> number
        
        With two arguments, equivalent to x**y.  With three arguments,
        equivalent to (x**y) % z, but may be more efficient (e.g. for ints). 
    >>> pow(3,2)            取3**2
    9
    >>> pow(3,2,5)        取3**2 % 5
    4
    >>> 

    round() 有两个参数,第一个参数返回浮点数,第二个参数取小数点的精度
    round(...)
        round(number[, ndigits]) -> number
        
        Round a number to a given precision in decimal digits (default 0 digits).
        This returns an int when called with one argument, otherwise the
        same type as the number. ndigits may be negative. 

    >>> round(3.1415,2)
    3.14
    >>>  

    callable()测试某个函数是否可以被调用。
    >>> callable(min)
    True
    >>> f = 100
    >>> callable(f)
    False
    >>> def f():
    pass
     
    >>> callable(f)
    True
    >>> 

    isinstance() 判断某个对象的类型
     
    >>> l
    [1, 2, 3, 45, 5, 7, 8, 324, 23, 4556, 32, 1234]
    >>> type(l)
    <class 'list'>
    >>> type([])
    <class 'list'>
     
    >>> if type(l) == type([]):
        print('ok')
     
        
    ok
    >>> isinstance(l,list)
    True
    >>> isinstance(l,int)
    False
    >>> 
     
    cmp()通常用来比较 两个字符串是否相等,注:python3.x已经移除这个内置函数 
     
    range() 快速生成一个序列
    xrange() 快速获取一个序列,返回一个对象(迭代器

    注:python3.x中,xrange()已经不存在了。range()返回一个迭代器 
    >>> a = range(10)
    >>> a
    range(0, 10)
    >>> list(a)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> tuple(a)
    (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
    >>> 

    类型转化函数
    type() 查看某个对象的类型
    int()转化为整型
    long()
    注:python3.x中,long()已经不存在了,跟int合并了。
    float()转化为浮点型
    complex()  复数
    str() 转化为字符串
    list() 转化为列表
    tuple() 转化为元组
    hex() 
    将一个整数转换为一个十六进制字符串
    oct()
    将一个整数转换为一个八进制字符串 
    chr()
    将一个整数转换为一个字符
    ord() 
    将一个字符转换为它的整数值 
  • 相关阅读:
    递归方法:对于树形结构的表,根据当前数据获取无限极的父级名称
    P
    A
    今年暑假不AC1
    J
    今年暑假不AC
    A
    *max_element函数和*min_element函数
    1199: 房间安排
    素数
  • 原文地址:https://www.cnblogs.com/fishdm/p/3574080.html
Copyright © 2011-2022 走看看