内置函数

1 all: 2 print(all([0,-2,3])) #判断所有的数据,非0就是True,有0就是False 3 >>> False 4 5 any: 6 print(any([1,0,-1])) #这里只要有一个为真就返回真 7 >>>True 8 9 ascii: 10 a = ascii([1]) 11 print(type(a),[a]) 12 >>><class 'str'> ['[1]'] #变成字符串 13 14 bin: 15 print(bin(255)) 16 >>>0b11111111 #将数字转换成2进制 17 18 boo: 19 print(bool(1)) 20 >>>True #跟"all","any"基本一样 21 22 bytearray: 23 a = bytearray("qwer",encoding="utf-8") 24 print(a) #可修改的二进制数据,只能用ascii码来修改 25 >>>bytearray(b'qwer') 26 27 bytes: 28 b = bytes("qwer",encoding="utf-8") 29 print(b) 30 >>>b'qwer' #不可修改的二进制数据 31 32 callable: 33 print(callable([])) #判断列表是否可调用(可调用的后面都能加()) 34 >>>False 35 36 chr & ord: 37 print(chr(99)) 38 >>>c #数字对应的ascii码,必须是数字 39 print(ord('q')) 40 >>>113 #与上相反 41 42 compile: 43 a = ''' 44 for i in range(10): 45 print(i) 46 ''' 47 compile_a = compile(a,'','exec') 48 exec(compile_a) #compile将字符串转成可执行内存对象,然后调用'exec'执行,但其实直接exec(a)也可以,所以不知道compile有什么卵用,为什么还要转换,MDZZ 49 >>>0 50 1 51 2 52 3 53 4 54 5 55 6 56 7 57 8 58 9 59 60 dir: 61 a = [] 62 print(dir(a)) 63 >>>['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__',.... #查询'list'有什么方法 64 65 divmod: 66 print(divmod(1000000,1)) 67 >>>(1000000, 0) #两数相除,返回商和余数 68 69 enumerate: 70 for i in enumerate(a): 71 print(i) #取下标 72 >>>(0, 1) 73 (1, 2) 74 (2, 3) 75 (3, 4) 76 (4, 5) 77 78 lambda: 79 a = lambda x:print(x) #匿名函数,你就想调用一次的时候可以使用,但匿名函数的智商有限,处理不了太复杂的东西 80 a('HEHE') 81 >>>HEHE 82 83 filter: 84 a = filter(lambda n:n>5,range(11)) #过滤出你想要的值 85 for i in a: 86 print(i) 87 >>>6 88 7 89 8 90 9 91 10 92 93 map: 94 a = map(lambda n:n*n,range(10)) 95 for i in a: 96 print(i) 97 >>>0 98 1 99 4 100 9 101 16 102 25 103 36 104 49 105 64 106 81 107 108 functools: 109 import functools 110 import functools 111 res = functools.reduce( lambda x,y:x+y,range(10)) 112 print(res) 113 >>>45 114 115 frozenset: 116 i = frozenset([1,2,3,]) #不可变集合 117 118 globals: 119 print(globals()) #以字典方式返回当前程序所有变量 120 121 hex: 122 print(hex(177)) 123 >>>0xb1 #转成16进制 124 125 hash: 126 hash('hehehe') #加密算法 127 128 id: 129 id(变量名) #返回内存地址 130 131 locals: 132 def local(): 133 local_1 = 'hehe' 134 print(locals()) 135 return 136 local() 137 >>>{'local_1': 'hehe'} #以字典的方式返回局部变量 138 139 oct: 140 print(oct(8)) 141 >>>0o10 #八进制 142 143 pow: 144 print(pow(2,8)) #返回2的八次方 145 >>>256 146 147 round: 148 print(round(1.5)) 149 >>>2 #四舍五入 150 151 sorted: 152 print(sorted(dic.items())) #排序,默认按照key排序 153 [(-100, 100), (-10, -10), (-1, 1), (1, 1), (10, 10), (100, 100)] 154 155 zip: 156 a = [1,2,3,4] 157 b = ['a','b','c','d'] 158 for i in zip(a,b): 159 print(i) #对应起来 160 >>>(1, 'a') 161 (2, 'b') 162 (3, 'c') 163 (4, 'd')