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

    一、内置函数

      内置函数是python解释器在运行之初就加载到当前工程中的函数,我们可以直接调用,前面我们用到的len()、range、min()、max()、input()、等都是内置函数。下面介绍我们之前没用到或者不常见的内置函数。以下是python中的内置函数。

      ['abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

    1.1作用域相关内置函数(globals()与locals())

      globals():获取的是全部全局变量的值并以字典的形式返回

      locals():获取当前作用域的全部局部变量的值并以字典的形式返回

    def fun1():
        a = 1
        print(locals())  #{'a':1}
        print(globals())  
    fun1()

     1.2字符串相关

      eval:执行字符串内的代码并返回结果,通常用来计算字符串计算代码:

    s1 = '1+2+3'
    print(eval(s1),type(eval(s1)))  #6 <class 'int'>

      exec:执行字符串代码,无返回值:

    s1 = '''
    for i in range(10):
    print(i)
    '''
    print(exec(s1))

     1.3输入输出相关

      输入输出相关的内置函数其实我们之前一直有在用,没错就是input和print.,但是之前我们只用了简单的方法,现在我们深入了解:

    input:函数接受一个输入数据返回类型为字符串,常用的方法在字符串章节已经使用过了,这里不再重复

    print:打印输出

      我们查看下print的使用介绍:

    def print(self, *args, sep=' ', end='
    ', file=None): # known special case of print
        """
        print(value, ..., sep=' ', end='
    ', file=sys.stdout, flush=False)
        
        Prints the values to a stream, or to sys.stdout by default.
        Optional keyword arguments:
        file:  a file-like object (stream); defaults to the current sys.stdout.
        sep:   string inserted between values, default a space.
        end:   string appended after the last value, default a newline.
        flush: whether to forcibly flush the stream.
        """
        pass

      从上面解释可以得知,print有个动态参数*args,说明可以接受多个参数,然后还有三个默认参数:sep、end、file 。sep表示多个参数直接的隔开符,默认是空格、end表示结束符,默认是换行符,file是文件句柄,可以对文件进行操作,下面依次举例:

    #sep
    print(11,22,33)
    print(11,22,33,sep=',')
    #运行结果:
    11 22 33
    11,22,33
    
    #end
    print(1,2,3)
    print(4,5,6)
    #运行结果:
    1 2 3
    4 5 6
    
    print(1,2,3,end='|')
    print(4,5,6)
    #运行结果:
    1 2 3|4 5 6

    #file
    f = open('a1.txt','w',encoding='utf-8')
    print(1111,file=f)

    #会将1111写入文件a1中

     1.4 hash()

      hash()是哈希算法的运用,哈希是把不可变数据类型哈希化生产一个唯一的值储存在内存中,我们知道字典的key就是哈希生成的。

     dic = {'name':'alex','kfdshjfhdskjfhsd': '123'}
     print(hash('name'))
     print(hash('name1'))
     print(hash('fdsmkfghsdlksld'))
     print(hash(1))
     print(hash(100))
     print(hash(100000000000))
     print(hash([1,2,3]))

    1.5 文件相关

      

    def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
        """
        Open file and return a stream.  Raise OSError upon failure.
        
        file is either a text or byte string giving the name (and the path
        if the file isn't in the current working directory) of the file to
        be opened or an integer file descriptor of the file to be
        wrapped. (If a file descriptor is given, it is closed when the
        returned I/O object is closed, unless closefd is set to False.)
        
        mode is an optional string that specifies the mode in which the file
        is opened. It defaults to 'r' which means open for reading in text
        mode.  Other common values are 'w' for writing (truncating the file if
        it already exists), 'x' for creating and writing to a new file, and
        'a' for appending (which on some Unix systems, means that all writes
        append to the end of the file regardless of the current seek position).
        In text mode, if encoding is not specified the encoding used is platform
        dependent: locale.getpreferredencoding(False) is called to get the
        current locale encoding. (For reading and writing raw bytes use binary
        mode and leave encoding unspecified.) The available modes are:

      文件操作open的使用在文件操作中已经说明过,这里不作详解。

    1.6 help()

      help是用来查找当前对象所拥有的方法(也就是函数功能)

    help(list)
    #运行结果:
        class list(object)
     |  list(iterable=(), /)
     |  
     |  Built-in mutable sequence.
     |  
     |  If no argument is given, the constructor creates a new empty list.
     |  The argument must be an iterable if specified.
     |  
     |  Methods defined here:
     |  
     |  __add__(self, value, /)
     |      Return self+value.
     |  
     |  __contains__(self, key, /)
     |      Return key in self.
     |  
     |  __delitem__(self, key, /)
     |      Delete self[key].
    。。。。。。。。。。。

     help会将该对象所有功能打印出来。

    1.7 callable

      检查一个对象是否是可调用的,我们知道函数是可以调用的,那么那些是不可以调用的,不可变数据就是不可调用的比如字符串:

    def fun1():
        return
    name = 'kingfan'
    print(callable(fun1))    #True
    print(callable(name))    #False

    1.8 数学相关

      bool :用于将给定参数转换为布尔类型,如果没有参数,返回False。

      int:函数用于将一个字符串或数字转换为整型。

      float:函数用于将整数和字符串转换成浮点数。

      bin:将十进制转换成二进制并返回。

      

    #    abs:函数返回数字的绝对值。
    print(abs(-1))    #1
    
    #    divmod:计算除数与被除数的结果,返回一个包含商和余数的元组(a // b, a % b)。 
    # print(divmod(12,7))  # (1, 5) (商,余数)
    
    #  round:保留浮点数的小数位数,默认保留整数,四舍五入。  ***
    # print(round(3.141592653,4))
    
    #  pow:求x**y次幂。(三个参数为x**y的结果对z取余) **
    # print(pow(2,5))
    # print(pow(2,5,12))
    
    #    sum:对可迭代对象进行求和计算(可设置初始值)。 *****
    #sum(iterable,start_num)
    # print(sum([1,2,3,4,100,101]))
    # print(sum([1,2,3,4,100,101],100))
    # print(sum([int(i) for i in [1,'2',3,'4','100',101]]))
    
    #  min:返回可迭代对象的最小值(可加key,key为函数名,通过函数的规则,返回最小值)。 *****
    # print(min([1,-2,3,4,100,101]))
    # print(min([1,-2,3,4,100,101]))
    # print(min([1,-2,3,4,100,101],key=abs))

      mix 和max的进阶用法:

    def min(*args, key=None): # known special case of min
        """
        min(iterable, *[, default=obj, key=func]) -> value
        min(arg1, arg2, *args, *[, key=func]) -> value
        
        With a single iterable argument, return its smallest item. The
        default keyword-only argument specifies an object to return if
        the provided iterable is empty.
        With two or more arguments, return the smallest argument.
        """
        pass

       从上面的介绍中我们知道min还可以传入一个函数,并将可迭代对象的每一个元素作为参数传给函数,并对其的函数返回值进行比较:

    # def func(x):
    # return x[1] # 1000 18 500

    # print(min([('alex',1000),('太白',18),('wusir',500)],key=func))  #('太白',18)

       首先我们分析min的*args接受的是[('alex',1000),('太白',18),('wusir',500)]这个参数,这个参数是可迭代对象,每个元素为('alex',1000)、('太白',18)、('wusir',500)。然后我们把这三个元素依次传给func ,然后func函数会返回x[1],也就是依次返回1000   18   500,这时min就会找到最小值18,而18是('太白',18)传入函数生成的,所以min最后返回的将结果就是('太白',18)

      总结: 

     # 1,他会将iterable的每一个元素当做函数的参数传进去。
    # 2,他会按照返回值去比较大小。
    # 3,返回的是 遍历的元素 x.
  • 相关阅读:
    实战分享 | 你知道这个死锁是怎么产生的吗?
    HDU 3016 线段树区间更新+spfa
    POJ 2828 线段树(想法)
    POJ 2184 01背包+负数处理
    HDU 2955 01背包(思维)
    HDU 1171 背包
    HDU 1561 树形DP入门
    POJ 3694 tarjan 桥+lca
    POJ 2446 最小点覆盖
    POJ 2226 最小点覆盖(经典建图)
  • 原文地址:https://www.cnblogs.com/Kingfan1993/p/9510121.html
Copyright © 2011-2022 走看看