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

    以上是Python官方文档中列出来的所有的内置函数。

    但是在Python3中通过dir(__builtins__)命令打印出来的所有的内置函数有156个,从abs开始算起,有75个。比上述列表显示的内置函数中增加的有:copyright(),credits(),debugfile(),dreload(),evalsc(),get_ipython(),license(),runfile().

    1.abs(x)

     1 Return the absolute value of a number. The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned.  #返回整型或浮点数的绝对值,如果参数是复数,返回其大小
     2 
     3 help(abs)
     4 Help on built-in function abs in module builtins:
     5 
     6 abs(x, /)
     7     Return the absolute value of the argument.
     8 
     9 abs(-11)
    10 Out[16]: 11
    11 
    12 abs(-11.11)
    13 Out[17]: 11.11
    14 
    15 abs(10+1j)   #复数返回其大小
    16 Out[18]: 10.04987562112089
    17 
    18 abs(-10+2j)
    19 Out[19]: 10.198039027185569

    2.all(iterable)

    Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:
    #如果可迭代对象中的所有元素都为True,则返回True;
    #如果可迭代对象中有一个元素为False,则返回False;
    #若果可迭代对象为空值,则返回True.
    help(all)
    Help on built-in function all in module builtins:
    
    all(iterable, /)
        Return True if bool(x) is True for all values x in the iterable.    
        If the iterable is empty, return True.
    
    def all(iterable):
        for element in iterable:
            if not element:   #如果不为假:返回False
                return False
        return True
    
    print(all([0,1]))
    [out] False

    3.any(iterable)

    Return True if any element of the iterable is true. If the iterable is empty, return False. 
    
    Help on built-in function any in module builtins:
    any(iterable, /)
        Return True if bool(x) is True for any x in the iterable.    
        If the iterable is empty, return False.
    #如果可迭代对象中的任一元素为真则为真(迭代对象为空,返回False).
    
    def any(iterable):
        for element in iterable:
            if element:
                return True
        return False
    
    print(any([0,1]))

    4.ascii(object)

    As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using x, u or U escapes. This generates a string similar to that returned by repr() in Python 2.
    #返回一个对象的可打印的字符串形式。
    
    
    ascii([1,2,3])
    Out[13]: '[1, 2, 3]'   #注意返回的整体是字符串形式
    
    ascii(['我们'])
    Out[14]: "['\u6211\u4eec']"

    5.bin(x)  

    Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
    #将整型数字转换为一个二进制字符串。
    
    bin(1)
    Out[17]: '0b1'
    
    bin(2)
    Out[18]: '0b10'
    
    bin(255)
    Out[19]: '0b11111111'
    
    bin(1934)
    Out[20]: '0b11110001110'

    6.class bool([x])

    Return a Boolean value, i.e. one of True or False.
     x is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True. The bool class is a subclass of int (see Numeric Types — int, float, complex). It cannot be subclassed further. Its only instances are False and True (see Boolean Values).
    
    bool([])
    Out[22]: False
    
    bool(0)
    Out[23]: False
    
    bool(None)
    Out[24]: False
    
    bool(not False)
    Out[26]: True

    7.class bytearray([source[, encoding[, errors]]])

    Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Bytearray Operations.
    #返回一个新的字节数组。类bytearray是一个可变的整数序列,范围在0 < = x < 256。它拥有大多数可变序列的常用方法,在可变序列类型中描述,以及字节类型所具有的大多数方法,可以看到字节和Bytearray操作。
    
    The optional source parameter can be used to initialize the array in a few different ways:
    #可选参数可以用几种不同的方式来初始化数组:
    
    If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
    #如果它是一个字符串,那么您还必须给出编码(以及可选的错误)参数;然后根据给定的str的编码来转化字字符串。
    
    If it is an integer, the array will have that size and will be initialized with null bytes.
    #如果它是一个整数,那么数组将具有这个大小,并且将用null字节进行初始化。
    If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
    #如果它是符合缓冲区接口的对象,那么将使用对象的只读缓冲区来初始化字节数组。
    If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.
    #如果它是一个可迭代的,那么它必须是range 0 < = x < 256的整数的迭代,它被用作数组的初始内容。
    Without an argument, an array of size 0 is created.
    #在没有参数的情况下,将创建一个大小为0的数组。
    
    See also Binary Sequence Types — bytes, bytearray, memoryview and Bytearray Objects.
    #还可以看到二进制序列类型——字节、bytearray、memoryview和bytearray对象。
    
    b=bytearray('abcde',encoding='utf-8')
    
    b[0]   #a的ascii码的数值
    Out[38]: 97
    
    b[1]  #b的ascii码的数值
    Out[39]: 98
    
    b[0]=100   #将b[0]改为ascii码数值为100的'd'
    
    b
    Out[41]: bytearray(b'dbcde')

    8.class bytes([source[, encoding[, errors]]])

    Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.
    #返回一个新的“字节”对象,这是一个不可变的整数序列,在range 0 < = x < 256。字节是bytearray的不可变版本——它具有相同的非变异方法和相同的索引和切片行为。
    
    Accordingly, constructor arguments are interpreted as for bytearray().
    
    Bytes objects can also be created with literals, see String and Bytes literals.
    
    See also Binary Sequence Types — bytes, bytearray, memoryview, Bytes Objects, and Bytes and Bytearray Operations.
    
    a=bytes('abcde',encoding='utf-8')
    
    a
    Out[31]: b'abcde'
    
    a.capitalize()
    Out[32]: b'Abcde'
    
    a
    Out[33]: b'abcde'

    9.callable(object)

    Return True if the object argument appears callable, False if not. If this returns true, it is still possible that a call fails, but if it is false, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a __call__() method.
    #如果对象参数看起来是可调用的,则返回True。
    
    New in version 3.2: This function was first removed in Python 3.0 and then brought back in Python 3.2.
    
    callable(list)
    Out[42]: True
    
    callable(abs)
    Out[43]: True
    #简单判断,对象后面可以加上()进行调用的就是callable。

    10.chr(i)

    Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string ''. This is the inverse of ord().
    #chr(i)中,返回对应整型i(unicode编码)的ascii码的字符
    返回的字符串代表一个字符的Unicode代码点整我。例如,科(97)返回字符串' a ',而科(8364)返回字符串“€”。这是ord()的倒数。
    
    The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.
    
    chr(97)
    Out[44]: 'a'
    
    chr(255)
    Out[45]: 'ÿ'
    
    chr(256)
    Out[46]: 'Ā'
    
    chr(1000)
    Out[47]: 'Ϩ'
    
    chr(1000000)
    Out[48]: 'U000f4240'
    
    chr(1114111)
    Out[53]: 'U0010ffff'
    
    chr(1114112)
    Traceback (most recent call last):
    
      File "<ipython-input-54-59208660f350>", line 1, in <module>
        chr(1114112)
    
    ValueError: chr() arg not in range(0x110000)

    11.classmethod(function) 暂时pass

    Return a class method for function.
    
    A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:
    
    class C:
        @classmethod
        def f(cls, arg1, arg2, ...): ...
    The @classmethod form is a function decorator – see the description of function definitions in Function definitions for details.
    
    It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.
    
    Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section.
    
    For more information on class methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

    12.compile(sourcefilenamemodeflags=0dont_inherit=Falseoptimize=-1)

    将源代码编译成代码或AST对象。代码对象可以由exec()或eval()执行。源可以是一个普通的字符串,一个字节字符串,或者一个AST对象。有关如何使用ast对象的信息,请参阅ast模块文档。

    文件名参数应该给出代码所读的文件;如果没有从文件中读取,传递一些可识别的值(' < string > '通常被使用)。

    模式参数指定什么样的代码必须被编译,它可以“执行”如果源由一系列的语句,“eval”如果它包含一个表达式,或“单一”如果它包括一个交互式的声明(在后一种情况下,表达式语句评估以外的东西都将打印)。

    如果编译的源是无效的,那么这个函数会引发语法错误,如果源包含null字节,则会出现ValueError。

     

    将源代码(字符串)编译成可以由exec()或eval()执行的代码对象。

    底层用于将代码进行编译的方法。

    a='for i in range(10):print(i)'#字符串类型的代码
    
    type(a)
    Out[57]: str
    
    compile(a,'','exec')
    Out[59]: <code object <module> at 0x00000000099F5270, file "", line 1>
    
    exec(compile(a,'','exec'))
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9

    但是上面两个例子,不需要编译也能直接执行。一般用于底层,目前未有应用场景的推荐。

    eval(code)
    Out[64]: 10.0
    
    exec(a)
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9

    13.class complex([real[, imag]])

    14.delattr(objectname)

    15.class dict(**kwarg)

    class dict(mapping**kwarg)

    class dict(iterable**kwarg)

    #dict() -> new empty dictionary
    dict()
    Out[67]: {}
    
    #dict(mapping) -> new dictionary initialized from a mapping object's
    (key, value) pairs
    mapping=(('name','zoe'),('age',18))
    
    dict(mapping)
    Out[73]: {'age': 18, 'name': 'zoe'}
    
    #dict(iterable) -> new dictionary initialized as if via:
    d = {}
    for k, v in iterable:
        d[k] = v
    
    #dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. 
    dict(name='zoe',age=18)
    Out[75]: {'age': 18, 'name': 'zoe'}

    16.dir([object])

    在没有参数的情况下,返回当前本地范围内的名称列表。有了一个参数,尝试返回该对象的有效属性列表。

    如果对象有一个名为__dir__()的方法,该方法将被调用,并且必须返回属性列表。这允许实现自定义__getattr__()或__getattribute__()函数来定制对其属性的报告。

    如果对象不提供__dir__(),那么函数将尽力从对象的__dict__属性中收集信息,如果定义了,并且从__dir__()。如果对象有一个__getattr__()时,那么返回的结果不一定是完整的。

    17.divmod(ab)

    将两个(非复数)数字作为参数,并返回两个由它们的商和余数组成的数字,当使用整数除法时。对于混合的操作和类型,二进制算术运算符的规则适用。

    对于整数来说,结果与(a / b,% b)相同。

    浮点数的结果是(q,a % b),q通常是数学。地板(a / b)但可能比那小1。在任何情况下,q * b + a % b非常接近a,如果% b是非零,它的符号是b,0 < = abs(a % b)< abs(b)。

    divmod(5,1) 
    Out[79]: (5, 0)   #返回(商,余数)
    
    divmod(5,2)
    Out[81]: (2, 1)

    18.enumerate(iterablestart=0)

    返回一个枚举对象。iterable必须是一个序列、迭代器或其他支持迭代的对象。枚举()返回的迭代器的__next__()方法返回包含计数的元组(从默认值到0),以及从迭代迭代中获得的值。

     1 a=range(10,100,20)
     2 
     3 enumerate(a)
     4 Out[92]: <enumerate at 0x9727090>
     5 
     6 for index,i in enumerate(a):
     7     print(index,i)
     8     
     9 0 10
    10 1 30
    11 2 50
    12 3 70
    13 4 90

    enumerate()方法可以用list()方法将索引和值输出:

    1 list(enumerate(a))
    2 Out[93]: [(0, 10), (1, 30), (2, 50), (3, 70), (4, 90)]
    3 
    4 list(enumerate(a,start=2))
    5 Out[94]: [(2, 10), (3, 30), (4, 50), (5, 70), (6, 90)]   
    6 #start用于设置初始索引位置,默认为0

    等价的方法:

    1 def enumerate(sequence, start=0):
    2     n = start
    3     for elem in sequence:
    4         yield n, elem   #迭代器
    5         n += 1

    19.eval(expressionglobals=Nonelocals=None)

    参数是字符串和可选的全局变量和局部变量。如果提供的话,globals一定是一个词典。如果提供,locals可以是任何映射对象。

    a=1
    
    eval('a+1')  #eval之可以执行简单的计算的expression
    Out[98]: 2

    20.exec(object[, globals[, locals]])

    该函数支持Python代码的动态执行。对象必须是字符串或代码对象。如果是字符串,则将字符串解析为Python语句的套件,然后执行(除非出现语法错误)。

    exec('for i in range(3):print(i)')
    0
    1
    2
    

     

    21.filter(functioniterable)

    过滤iterable中的函数符合为True的值。

     1 filter(lambda n:n>5,range(10))
     2 Out[102]: <filter at 0x9a0ba90>
     3 
     4 res=filter(lambda n:n>5,range(10))
     5 for i in res:
     6     print(i)
     7     
     8 6
     9 7
    10 8
    11 9

    22.map(functioniterable...)

    1 for i in map(lambda n:n+1,range(5)):   #等价于 [n+1 for n in range(5)]
    2     print(i)
    3     
    4 1
    5 2
    6 3
    7 4
    8 5

    注意:filter()和map()的区别在于

    附加介绍reduce()。在python2中reduce()函数是内置函数,在3.x中在functools模块中。

    import functools
    
    res=functools.reduce(lambda x,y:x+y,range(10))
    res   #1+2+3+4...+10
    Out[3]: 45
    
    help(functools.reduce)
    Help on built-in function reduce in module _functools:
    
    reduce(...)
        reduce(function, sequence[, initial]) -> value
        
        Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.
        For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.

      

     23.class float([x])

    从数字或字符串x中返回一个浮点数。

     1 float(1)
     2 Out[7]: 1.0
     3 
     4 float('+1')
     5 Out[8]: 1.0
     6 
     7 float('-1')
     8 Out[9]: -1.0
     9 
    10 float('1e-003')
    11 Out[10]: 0.001
    12 
    13 float('nan')
    14 Out[11]: nan
    15 
    16 float('+1e6')
    17 Out[12]: 1000000.0
    18 
    19 float('infinity')
    20 Out[13]: inf

    24.format(value[, format_spec]

    25.class frozenset([iterable])

     将iterable对象转换为不可变的集合。

    frozenset()的对象的方法仅有以上方法,pop()等方法对集合进行变化操作的方法都没有了。

    26.getattr(objectname[, default])

    27.globals()

    返回的是当前程序中的所有变量,所有变量存储在字典中。

    28.hasattr(objectname)

    29.hash(object)

    固定的映射关系

    一旦字符串映射给定了一个固定的值,就永远都是这个值不会发生变化。

    30.help([object])

    31.hex(x)

     将数字转换成16进制。

    1 hex(255)
    2 Out[31]: '0xff'
    3 
    4 hex(10)
    5 Out[32]: '0xa'

    32.id(object)

    返回内存地址。

    33.input([prompt])

    34.class int(x=0)

    class int(xbase=10)

    35.isinstance(objectclassinfo)

    36.issubclass(classclassinfo)

    37.iter(object[, sentinel])

    38.len(s)

    39.class list([iterable])

    40.locals()

    更新并返回代表当前本地符号表的字典。

    1 def test():
    2     local_var=333
    3     print(locals())
    4    
    5 test()
    6 {'local_var': 333}
    7 
    8 print(globals().get('local_var'))  #globals()中不返回locals()的对象
    9 None

    41.map(functioniterable...)

    42.max(iterable*[, keydefault])

    max(arg1arg2*args[, key])

    43.memoryview(obj)

    44.min(iterable*[, keydefault])

    min(arg1arg2*args[, key])

    45.next(iterator[, default])

    相当于迭代器中的__next__()方法。

    46.class object

    python中一切皆对象,通过' . '调用其属性(功能,方法)。

    47.oct(x)

    将整数转换为八进制字符串。

    1 oct(0)
    2 Out[47]: '0o0'
    3 
    4 oct(8)
    5 Out[48]: '0o10'  #逢8进1

    48.open(filemode='r'buffering=-1encoding=Noneerrors=Nonenewline=Noneclosefd=Trueopener=None)

    49.ord(c)

    给定一个字符串表示一个Unicode字符,返回一个整数表示该字符的Unicode代码点。

    是chr()的倒数。

    1 ord('z')
    2 Out[51]: 122
    3 
    4 ord('')
    5 Out[52]: 8364

    50.pow(xy[, z])

    pow(100,2,5)  #pow(x, y) % z
    Out[54]: 0
    pow(100,2,3)
    Out[56]: 1
    
    pow(100,2)  #返回x的y次方。x**y
    Out[57]: 10000

    51.print(*objectssep=' 'end=' 'file=sys.stdoutflush=False)

    52.class property(fget=Nonefset=Nonefdel=Nonedoc=None)

    53.range(stop)

    range(startstop[, step])

    54.repr(object)

    用字符串的形式表示对象。

    1 a
    2 Out[58]: frozenset({1, 2})
    3 
    4 repr(a)
    5 Out[59]: 'frozenset({1, 2})'

    55.reversed(seq)

    56.round(number[, ndigits])

    round(1.333339,3)
    Out[61]: 1.333

    57.class set([iterable])

    58.setattr(objectnamevalue)

    59.class slice(stop)

    class slice(startstop[, step])

    切片

    60.sorted(iterable[, key][, reverse])

     1 dict1={6:2,8:0,1:4,-5:6,99:11,4:22}
     2 
     3 print(dict1)
     4 {6: 2, 8: 0, 1: 4, -5: 6, 99: 11, 4: 22}
     5 
     6 sorted(dict1)
     7 Out[68]: [-5, 1, 4, 6, 8, 99]
     8 
     9 print(sorted(dict1))
    10 [-5, 1, 4, 6, 8, 99]
    11 
    12 print(sorted(dict1.items()))  #默认的key是字典的key,输出key-value组成的元组的列表。
    13 [(-5, 6), (1, 4), (4, 22), (6, 2), (8, 0), (99, 11)]

    因为字典是无序的,所以默认按照字典的key返回的值是在列表中。

    如果想要字典按value进行排序,则可以:

    print(sorted(dict1.items(),key=lambda x:x[1]))   #用key指定按哪个值进行排序,这指定(k,v)中的value
    [(8, 0), (6, 2), (1, 4), (-5, 6), (99, 11), (4, 22)]

    61.staticmethod(function)

    62.class str(object='')

    class str(object=b''encoding='utf-8'errors='strict')

    63.sum(iterable[, start])

    64.super([type[, object-or-type]])

    65.tuple([iterable])

    66.class type(object)

    class type(namebasesdict)

    python中的所有数据类型都是从type中产生的。

    67.vars([object])

    返回一个对象的所有属性名。

    68.zip(*iterables)

    1 for i in zip(a,b):  #zip(a,b)返回迭代器,用for查看。
    2     print(i)
    3     
    4 (1, 'a')
    5 (2, 'b')
    6 (3, 'c')
    7 (4, 'd')

    如果两个对象的元素不是一一对应的,则按最少的来。

    for i in zip([1,2,3],[4,5]):
        print(i)
        
    (1, 4)
    (2, 5)
    

    69.__import__(nameglobals=Nonelocals=Nonefromlist=()level=0)

    import decorator
    
    __import__('decorator')  #等价上面的方法
    Out[82]: <module 'decorator' from 'C:\Users\zoe\Anaconda3\lib\site-packages\decorator.py'>

     

  • 相关阅读:
    video标签
    正则表达式
    BOM和DOM
    css样式属性
    js简介
    格式与布局
    CSS样式表
    表单
    redis学习心得之三-【java操作redis】
    redis学习心得之二【redis主从配置】
  • 原文地址:https://www.cnblogs.com/zoe233/p/7083286.html
Copyright © 2011-2022 走看看