python内置函数详解

    xiaoxiao2023-10-19  148

    python内置函数详解

    内置函数:

    all

    Return True if bool(x) is True for all values x in the iterable. 如果可迭代对象中的所有元素都是True,则结果为True, If the iterable is empty, return True. 如果可迭代对象为空,返回的也是True

    #all()这个方法详解 def all(iterable): for element in iterable: if not element: return False return True boolean = all([]) print(boolean) #True boolean = all([0,1,2,-1,-2]) print(boolean) #False

    abs

    Return the absolute value of the argument. 返回参数的相反的值

    #def abs(*args,**kwargs): # pass #案例讲解 num = abs(-1) print(num)

    any

    Return True if bool(x) is True for any x in the iterable. 在可迭代对象中只要有一个元素返回真,则函数返回真 If the iterable is empty, return False. 如果可迭代对象是空的,什么元素都没有,则返回False

    def any(*args, **kwargs): pass #完整写法 def any(iterable): for element in iterable: if element: return True return False #案例讲解: boolean = any([0,0,1]) print(boolean) #True boolean = any([0,0,0]) print(boolean) #False

    ascii,编程字符串对象

    a = ascii([1,2,"你好"]) print(a) # print(type(a),[a]) #type()查看数据的类型,此时为字符串类型

    bin

    Return the binary representation of an integer. 返回显示十进制的二进制 >>> bin(2796202) ‘0b1010101010101010101010’

    binary_num = bin(2) print(binary_num)

    bytearray

    bytearray:把二进制变成可以修改的列表

    a = bytes("abc",encoding="utf-8") print(a.upper(),a) #可见二进制是不可以修改的 b = bytearray("abc",encoding="utf-8") print(b[0]) b[0] = 100 print(b) #dbc

    chr

    Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff 把数字所对应的ascii码(字符串,数字,特殊符号)给打印出来

    print(chr(97)) #a

    ord

    Return the Unicode code point for a one-character string 返回这个字符的Unicode编码

    print(ord("a")) # 97

    compile

    compile把字符串变成一个可执行的.py对象

    code = "for i in range(10): print(i)" c = compile(code,"","exec") exec(c) exec() #把字符串变成可执行的代码 a = exec("for i in range(10):print(i)") #可以把字符串中的代码执行 print(a)

    eval

    把简单的字符串运算式(加减乘除,三元运算等)变成可执行的Python代码,不能执行for循环比较难的表达式(exec函数却可以,上面的例子)

    e = eval("1+2/3*2") print(e) #把上面运算式的结果给打印出来

    dir()

    返回各个数据类型可以用的方法名称

    print(dir([]))

    divmod

    divmod():Return the tuple (x//y, x%y) 返回两个数的 商和余数

    print(divmod(5,3)) #(1,2)

    enumerate

    enumerate():可以给迭代对象的元素添加下标

    str1 = "abcdef" for index,i in enumerate(str1): print(index, i)

    lambda

    额外补充的内容:匿名函数 lambda:数学上的一个表达式

    calc = lambda n:print(n**2) calc(3)

    filter, map

    ‘’’ lambda可以和filter结合着用 filter:即过滤器,根据所给的条件,过滤相应的内容 lambda可以和map结合着用

    ‘’’

    res = filter(lambda n:n>5,range(10)) # res = map(lambda n:n*2,range(10)) #[i*2 for i in range(10)]是一样的 for i in res: print(i)

    globals

    globals:返回整个文件中的所有的变量相对应的键值对

    print(globals())

    hash

    hash():散列

    a = {6:2, 8:0, 1:4, -5:6, 99:11, 4:22} print(sorted(a.items())) #使键按照大小排序 print(sorted(a.items(), key=lambda x:x[1])) #按照字典的值进行排序 print(a)

    zip

    zip():拉链

    a = [1,2,3,4,5,6] b = ['a','b','c','d'] for i in zip(a,b): print(i)

    持续更新,不断学习,继续努力,加油~

    最新回复(0)