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

    python3.6常用的内函数Built-in Functions有哪些:

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

    如何查看builtins模块

    import builtins
    dir(builtins)
    



    容器类型

    list()

    list(Iterable) 先将Iterable对象转换成迭代器,再调用next()方法,每得到一个值就将它传给list列表。直到没有元素报出StopIteration。并捕获该异常。返回的列表也是一个可迭代对象。

    print(list((1,2,3)))  #[1, 2, 3]
    

    tuple()

    tuple初始化元组本质和列表类似。

    print(tuple((1,2,3)))  #(1, 2, 3)
    

    dict()

    dict初始化元组本质和列表类似。
    dict()也可以接收一个可迭代对象。具体例子看zip()

    print(dict(a=1,b=2))   #{'a': 1, 'b': 2}
    

    set()

    set初始化元组本质和列表类似。

    set(Iterable)

    print(set([1,2,3]))   #(1,2,3)
    

    frozenset()

    frozenset初始化元组本质和列表类似。

    frozenset(Iterable)

    frozenset()和set()的区别,set是可变集合,而frozenset是不可变集合,也就是说frozenset一旦生成,就不能再添加元素或修改元素。

    print(frozenset([1,2,3]))   #(1,2,3)
    

    len()

    Return the number of items in a container.

    print(len({"a":1,"b":2,"c":3,"d":4}))   #4
    



    迭代

    迭代:也就是重复做一件事

    iter()

    iter(Iterable) 将可迭代对象转换成迭代器。
    等价于object.__iter__()。
    如果对象内置了__iter__(),那它本身就是可迭代对象。
    如果同时内置了__next__(),那它就是迭代器。

    
    
    

    结果:

    
    

    next()

    next()获取迭代器下一个值。如果没有值可取,则报出StopIteration。

    
    
    

    结果:

    
    

    enumerate()

    enumerate(Iterable,start=0)从start开始,每从可迭代对象获取一个值,就将整型序号和该值打包成一个元组。返回一个enumerate对象,是一个迭代器。

    dic={"a":1,"b":2,"c":3,"d":4}
    for i in enumerate(dic,2):
        print (i)
    
    

    结果:

    (2, 'a')
    (3, 'b')
    (4, 'c')
    (5, 'd')
    

    range()

    生成一个range对象(可迭代对象)

    range(1,9,2)  #1 3 5 7
    range(9,1,-2)  #9 7 5 3
    

    zip()

    zip(Iterable1,Iterable2,...,IterableN)
    每次从所有可迭代对象分别取一个值,打包成元组。直到其中一个可迭代对象没有元素可取为止。返回的是一个zip对象。实际上是一个迭代器。

    a=(1,2,3,4)
    b="hello"
    c=["a","b","c","d","e","f"]
    d=["a","b","c","d","e","f"]
    e=["a","b","c","d","e","f"]
    f=["a","b","c","d","e","f"]
    for i in zip(a,b,c,d,e,f):
        print(i)
    

    结果:

    (1, 'h', 'a', 'a', 'a', 'a')
    (2, 'e', 'b', 'b', 'b', 'b')
    (3, 'l', 'c', 'c', 'c', 'c')
    (4, 'l', 'd', 'd', 'd', 'd')
    

    zip()和dict()的结合使用:

    a=(1,2,3,4)
    b="hello"
    print(dict(zip(a,b)))
    

    结果:

    {1: 'h', 2: 'e', 3: 'l', 4: 'l'}
    



    判断bool值一类

    bool()

    bool只有两个值True和False。
    真(True):非空容器,非空字符串,非0的数字。
    假(False):空容器,空字符串,0,None

    all()

    all(Iterable)    Iterable自身为空,返回True。但Iterable里的元素只要有一个bool值为False,就返回False

    li=[]
    print(all(li))   #True
    li=[1," "]       #bool(" ") 返回True
    print(all(li))  #True
    li=["",1," "]     #bool("") 返回False
    print(all(li))  #False
    

    any()

    any(Iterable)    Iterable自身为空,返回False。但Iterable里的元素只要有一个bool值为True,就返回True

    li=[]
    print(any(li))   #False
    li=["",None]
    print(any(li))     #False
    li=["",None," "]
    print(any(li))    #True
    

    callable()

    只要对象是可调用的(函数和类),就返回True

    print(callable(print))   # True
    



    数字

    int()

    整形int

    i=1    #本质上是使用i=int(1),int作为一个工厂函数,批量生产int数据类型
    i=int(1)
    i=int("123")  #可以将一个字符串组成的整数转换成整形
    i=int(123.1)   #去尾求整
    i=int("100",base=2)   #print:4
                          #将一个字符串组成的整数以对应的进制换算成十进制数
    

    bin()

    将十进制数转换成二进制数并打包成str类型返回。

    print(bin(9))  #0b1001   一个str数据类型
    print(type(bin(9)))   #<class 'str'>
    print(bin(9)[2:])   #1001
    

    hex()

    将十进制数转换成十六进制数并打包成str类型返回。

    print(hex(115))    #0x73
    

    oct()

    将十进制数转换成八进制数并打包成str类型返回。

    print(oct(115))    0o163
    

    abs()

    求绝对值

    abs(-1)   #1
    

    pow()

    求指数

    print(pow(3,2))   #3**2=9
    print(pow(3,2,2))    #3**2%2=1   #适用于网页的分页
    

    divmod()

    divmod(x,y)      return    (x//y,x%y)

    print(divmod(10,3))   #  (3, 1)
    

    round()

    四舍六入五成双

    print(round(8.5))   #8
    print(round(9.5))    #10
    print(round(10.5))   #10
    
    print(round(10.6))   #11
    
    print(round(10.55,1))  #10.5   1表示保留一位小数
    
    print(round(10.555,2))  #10.56   2表示保留二位小数
    
    

    上面的并不是错误,因为计算机的原因,并不能将十进制数字0.1转换成二进制浮点数,所以大多小数和分数并不能精确的表达。

    print(round(14,-1))  #10
    print(round(15,-1))  #20
    
    print(round(50,-2))   #0
    print(round(60,-2))    #100
    

    -1表示小数点前的第1位四舍五入(五舍六入),-2表示小数点前的第2位四舍五入(五舍六入)。结果并不准确

    float()

    浮点数,float32小数点后7位有效,float64小数点后15位有效

    使用方法参照int()

    如果要精确比较浮点数大小,请使用decimal模块。

    complex()

    定义虚数

    c=1-2j
    print(c.real,c.imag)  #1.0 -2.0
    c=complex(1,2j)
    print(c.real,c.imag)  #1.0 -2.0
    



    编码和字符

    bytes()

    将十进制数转换成二进制数并打包成str类型返回。

    print(bytes('hello',encoding="utf-8"))   #b'hello'
    print("hello".encode("utf-8"))    #b'hello'
    

    chr()

    返回该编号对应的unicode编码的字符

    print(chr(65))  #"A"
    print(chr(20013))  #中
    

    ord()

    ordinal

    返回该字符对应的unicode编号

    print(ord("中"))  #20013
    
    

    ascii()

    这个函数跟repr()函数一样,返回一个可打印的对象字符串方式表示。
    当遇到非ASCII码时,就会输出x,u或U等字符来表示。与Python 2版本里的repr()是等效的函数。
    所以ascii()返回的值通常可以被eval()执行的。

    print(ascii("中国"))   #u4e2du56fd
    print(eval(ascii("中国")))
    

    结果:

    'u4e2du56fd'
    中国
    

    str()

    str(object='') -> str
    str(bytes_or_buffer[, encoding[, errors]]) -> str

    将一个object转换成str对象。str对象是一个可迭代对象

    print(bytes("中国",encoding="utf-8"))
    print(str(b'xe4xb8xadxe5x9bxbd'))
    print(str(b'xe4xb8xadxe5x9bxbd',encoding="utf-8"))
    

    结果:

    b'xe4xb8xadxe5x9bxbd'
    b'xe4xb8xadxe5x9bxbd'
    中国
    

    repr()

    repr()返回的是标准字符串
    repr(),也就是representation及描述的意思。,不是对人的描述,而是对python机器的描述,也就是它会将某物返回一个它在python中的描述。

    print(str("ABC"))   #ABC
    print(repr("ABC"))  #'ABC'
    print(type(repr("ABC")))  #<class 'str'>
    

    str()和repr()都是将object转换为str数据类型。他们两的区别是,函数str() 用于将值转化为适于人阅读的形式,而repr() 转化为供解释器读取的形式。

    eval(repr("ABC"))
    eval(str("ABC"))   #会报错
    
    

    repr()函数得到的字符串通常可以用来重新获得该对象,repr()的输入对python比较友好。通常情况下obj==eval(repr(obj))这个等式是成立的。

    print(repr("AB")+"C")   #'AB'C
    
    

    print()

    python中的print()能把常见类型的对象打印成一串文字,甚至包括列表、字典、元组等。自己定义的函数和自己所建的类的实例,print()打印的是它们在内存中的地址
    这在其他语言里是做不到的。

    总结:Python中出现的任何中文,虽然我们在编辑器里看到的是中文,但是背地里全是一串编码。

    bytearray()

    bytearray(iterable_of_ints) -> bytearray
    bytearray(string, encoding[, errors]) -> bytearray
    bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
    bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
    bytearray() -> empty bytes array

    Construct a mutable bytearray object from:

    • an iterable yielding integers in range(256)
    • a text string encoded using the specified encoding
    • a bytes or a buffer object
    • any object implementing the buffer API.
    • an integer
      # (copied from class doc)



    高阶函数

    在python里,函数作为第一类对象,可以将函数作为形参传给另一个函数。接收其他函数作为形参,这样一种函数就叫高阶函数。
    内置函数中,高阶函数除了map()reduce()filter(),还有sorted()max()min()

    map()

    map,也叫映射。
    map(function,Iterable)
    map实现的功能是,先将Iterable对象转换为迭代器,再每next()一次,获取到的值作为function的形参,运算后的返回值给map接收。而最后得到的"map object",本质上也是一个迭代器。

    m=map(lambda x:x**3,[1,2,3,4])
    print(list(m))
    

    结果:

    [1, 8, 27, 64]
    

    reduce()

    reduce,也就是合并。python3在使用reduce函数前,需从functools模块导入。
    reduce(function, sequence[, initial]) -> value
    在python3中,
    reduce实现的功能是,如果没有初始值,先将从序列获取两个值,获取到的值作为function的形参,运算后的返回值和下一次从序列得到的一个值再作为前面函数的参数。依此循环,最后得到一个结果返回给reduce。如果有初始值,第一次只从序列获取一个值,和初始值传给function作为2个形参,返回一个结果与下一次从序列获取的得到的一个值再次作为function的形参。依此循环,最后得到一个结果返回给reduce。

    from functools import reduce
    
    print(reduce(lambda x,y:x+y,range(10),10))
    

    结果:

    55
    

    filter()

    filter,也叫过滤。
    filter(function,Iterable)
    filter函数实现的功能是,先将Iterable对象转换为迭代器,再每next()一次,获取到的值作为function的形参,运算后的返回值若果是True,就传给filter。如果是False,就舍弃。而最后得到的"filter object",本质上也是一个迭代器。

    f=filter(lambda a:a>5,range(11))
    print(list(f))
    

    结果:

    [6, 7, 8, 9, 10]
    



    排序

    sorted()

    sorted(Iterable)
    默认按升序(ascending)排
    不仅可以对整形、浮点型数排序,还可以对unicode字节或bytes字节进行排序(也就是说unicode只能和unicode排序,其他类型只要是x就可以排序,如gbk和utf-8是可以比较大小的)。

    sorted(Iterable,key=function)
    sorted(Iterable,reverse=True)
    按降序(descending)排
    sorted的返回值是排完之后的结果。
    python中的Operator模块可以用来排序。

    • 对uincode、bytes排序
    l=["中国","中华"]
    print(ascii("中国"))
    print(ascii("中华"))
    print(sorted(l))
    
    
    a="中国".encode("utf-8")
    b="中华".encode("utf-8")
    li=[a,b]
    print(sorted(li))
    

    结果:

    'u4e2du56fd'
    'u4e2du534e'
    ['中华', '中国']
    [b'xe4xb8xadxe5x8dx8e', b'xe4xb8xadxe5x9bxbd']
    
    • 使用函数来排序
    #通过年龄来排序
    li=[{"name":"alen","age":18},
         {"name":"mikasa","age":17},
         {"name":"levi","age":20}
        ]
    
    print(sorted(li,key=lambda x:x["age"]))
    

    结果:

    [{'name': 'mikasa', 'age': 17}, {'name': 'alen', 'age': 18}, {'name': 'levi', 'age': 20}]
    
    • 降序排列
    li=[2,6,5,3,9,4,1,2,10]
    print(sorted(li,reverse=True))
    

    结果:

    [10, 9, 6, 5, 4, 3, 2, 2, 1]
    
    • sorted()和sort()方法的区别
    li=[2,6,5,3,9,4,1,2,10]
    print(sorted(li))   #返回值是排完之后的结果
    print(li)    #sorted()并不会改变对象里的元素顺序。
    print(li.sort())   #返回值为None
    print(li)   #对象.sort(),对象自身的元素顺序也会被改变
    

    结果:

    [1, 2, 2, 3, 4, 5, 6, 9, 10]
    [2, 6, 5, 3, 9, 4, 1, 2, 10]
    None
    [1, 2, 2, 3, 4, 5, 6, 9, 10]
    

    结论:

    1. sorted()方法排序后,有返回值,返回的是排好以后的序列。但原序列的元素顺序并不会改变。
    2. sort()方法无返回值。原序列的元素顺序会发生改变。

    max()

    python里的比较大小和排序一样,都能对数字、字符串排序或比较大小。而且还能对unicode字节或bytes字节排序或比较大小。除此之外,也能通过自定义的函数排序或比较大小。

    max(iterable, *[, default=obj, key=func]) -> value

    默认值是当iterable为空时,才返回default的值。

    max(arg1, arg2, *args, *[, key=func]) -> value

    • 选出bytes里最大的一个
    a="中国".encode("utf-8")
    b="中华".encode("utf-8")
    c="国家".encode("gbk")
    d=ascii("中国")
    
    
    li=[a,b,c]
    #li=[a,b,c,d]   #TypeError: '>' not supported between instances of 'str' and 'bytes'
    print(li)
    print(max(li))
    

    结果:

    [b'xe4xb8xadxe5x9bxbd', b'xe4xb8xadxe5x8dx8e', b'xb9xfaxbcxd2']
    b'xe4xb8xadxe5x9bxbd'
    
    • 通过函数来筛选
    li=["aLex","Alen","Levi"]
    
    print(max(li,key=lambda x:x.lower()))
    

    结果:

    Levi
    

    min()

    python里的比较大小和排序一样,都能对数字、字符串排序或比较大小。而且还能对unicode字节或bytes字节排序或比较大小。除此之外,也能通过自定义的函数排序或比较大小。

    min的使用情况和max完全一样,只是一个返回最小值,一个返回最大值。这里不再举例。具体使用方法,参考max()

    reversed()

    reversed(sequence) -> reverse iterator over values of the sequence

    Return a reverse iterator




    编译相关

    查看对compile、exec、eval、locals和globals的使用:
    http://www.cnblogs.com/yyds/p/6276746.html?utm_source=itdadao&utm_medium=referral

    compile()

    code="for i in range(5):print(i,end=" ")"
    cmpcode=compile(code,"","exec")
    exec(cmpcode)
    

    结果:

    0
    1
    2
    3
    4
    
    
    s="3+4"
    a=compile(s,"","eval")
    print(eval(a))
    

    结果:

    7
    

    exec()

    动态执行Python代码。也就是说exec可以执行复杂的Python代码,而不像eval函数那么样只能计算一个表达式的值。

    eval()

    将字符串中的表达式提取出来,再执行。只能是单个运算表达式(注意eval不支持任意形式的赋值操作),而不能是复杂的代码逻辑

    s="{'a':1,'b':2}"
    print(eval(s))
    

    结果:

    {'a': 1, 'b': 2}
    



    命名空间

    locals()

    Return a dictionary containing the current scope's local variables.

    NOTE: Whether or not updates to this dictionary will affect name lookups in
    the local scope and vice-versa is implementation dependent and not
    covered by any backwards compatibility guarantees.

    vars()

    vars([object]) -> dictionary

    Without arguments, equivalent to locals().
    With an argument, equivalent to object.__dict__.

    globals()

    Return the dictionary containing the current scope's global variables.
    NOTE: Updates to this dictionary *will* affect name lookups in the current
    global scope and vice-versa.

    \_\_import\_\_()

    当需要导入以字符串命名的模块时,可以使用此函数。

    import time
    print(time.time())
    

    结果:

    1492245303.2760558
    

    上面用import导入等价于

    ti=__import__("time")
    print(ti.time())
    

    结果:

    1492245534.7555227
    



    object

    classmethod

    staticmethod

    getattr

    setattr

    hasattr

    delattr

    issubclass()

    判断一个类是不是另一个类的子类

    class A:pass
    
    class B(A): pass
    
    print(issubclass(B,A))   #True
    

    super

    property




    类型

    type()

    查看对象的type

    i=int()
    print(type(i))
    print(type(int))
    print(type(print))
    #判断i是否是整形
    print(type(i) is int)   #等价于isinstance(i,int)
    

    结果:

    <class 'int'>
    <class 'type'>
    <class 'builtin_function_or_method'>
    True
    

    isinstance()

    isinstance(x, A_tuple)
    判断一个对象是否是元组中是某个类或其超类的实例。

    i=int()
    print(isinstance(i,int))
    
    print(isinstance(i,(int,str)))
    

    结果:

    True
    True
    



    帮助文档查看

    help()

    调用内置的帮助系统。如果参数是一个字符串,字符串查找 作为一个模块的名称,函数,类,方法,关键字,或文档 话题,帮助页面打印在控制台上。

    help(sum)
    

    result:

    Help on built-in function sum in module builtins:
    
    sum(iterable, start=0, /)
        Return the sum of a 'start' value (default: 0) plus an iterable of numbers
        
        When the iterable is empty, return the start value.
        This function is intended specifically for use with numeric values and may
        reject non-numeric types.
    
    

    dir()

    如果对象有一个名为的方法__dir__(),这个方法将被调用 必须返回属性的列表。 这样就可以实现一个自定义的对象__getattr__()或__getattribute__()功能定制dir()报告它们的属性。
    以列表形式返回该对象的所有属性和方法

    print(dir(sum))
    

    result:

    ['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
    
    

    其他

    hash()

    Return the hash value for the given object.

    Two objects that compare equal must also have the same hash value, but the
    reverse is not necessarily true.

    用来校验数据使用。

    1. 字符串如果改变,得到的hash值也不一样
    2. 只要用同一个算法,返回的hash值得长度永远不变
    3. 哈希值不能逆推。

    open()

    打开一个文件对象,返回一个文件句柄。可以通过这个句柄来操作文件。而且该句柄是一个可迭代的对象。

    memoryview()

    id()

    Return the identity of an object.

    This is guaranteed to be unique among simultaneously existing objects.
    (CPython uses the object's memory address.)

    返回的是唯一的身份标识号(并不等于是内存地址)。
    在python3中,字符串在内存中是共享的,在创建字符串时,先看是否有创建过相同的字符串,如果有,就绑定该字符串内存地址。如果没有,再在内存中开辟一个空间,来存放新的字符串。
    而对于int,-5~256都是共享内存的,超过以后,就不共享了。
    判断两个变量的id是否相等,用is

    a=256
    b=256
    c=1000
    d=1000
    print(id(a))
    print(id(b))
    print(a is b)
    print(c is d)
    

    结果:

    1381680192
    1381680192
    True
    False
    
  • 相关阅读:
    BZOJ3566: [SHOI2014]概率充电器
    BZOJ5018: [Snoi2017]英雄联盟
    BZOJ4627: [BeiJing2016]回转寿司
    BZOJ4719: [Noip2016]天天爱跑步
    BZOJ1511: [POI2006]OKR-Periods of Words
    BZOJ4721: [Noip2016]蚯蚓
    BZOJ1922: [Sdoi2010]大陆争霸
    BZOJ2525: [Poi2011]Dynamite
    单选按钮 / 复选框 样式自定义
    HDU 产生冠军 2094
  • 原文地址:https://www.cnblogs.com/yangzhenwei123/p/6759250.html
Copyright © 2011-2022 走看看