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() | insubclass() | 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() |
- abs() 取绝对值
- dict() 把一个数据转成字典
- help() 帮助
- min() 从列表中取出最小数
>>> a = [1,4,5,-1,3] >>> min(a) -1
- max() 从列表中取出最大数
>>> a = [1,4,5,-1,3] >>> max(a) 5
- all() 如果bool(x)为True,即x中所有元素均为True,all(x)为True。如果x是可循环的(列表为可循环的),all(x)也返回True。
空列表或列表内元素全为True,all()为True。
#一种特殊情况 >>> bool([]) False >>> all([]) True
- any()
#和all相反,只要有列表中有一个元素为True,any即为True >>> any([False,0]) False >>> any([False,0,1]) True >>> any([]) False
- dir() 打印当前程序中存在的所有变量
>>> dir() ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__'] #系统自带变量 >>> dir(__builtins__) #打印所有的内置模块 ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', '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']
- vars() 打印当前所有变量名及其对应的值
>>> vars() {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 's': frozenset({2, 3, 4, 5}), 'f': <function f at 0x000002C11182F7B8>, 'lis': [1, 2, 3]}
- locals() 在函数里面运行,打印函数里所有的局部变量名及其值
>>> def f(): ... n = 3 ... print(locals()) ... >>> f() {'n': 3}
- globals() 打印所有全局变量名及其值
>>> globals() {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 's': frozenset({2, 3, 4, 5}), 'f': <function f at 0x000002C1118359D8>, 'lis': [1, 2, 3]}
- hex() 将数字转换成十六进制
- slice() 切片:相当于提前定义好切片要求
>>> l = list(range(10)) >>> l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> s = slice(1,7,2) >>> s slice(1, 7, 2) >>> l[1:7:2] [1, 3, 5] >>> l[s] [1, 3, 5]
- divmod() 取整除和余数
>>> 10//3 3 >>> 10/3 3.3333333333333335 >>> 10%3 1 >>> divmod(10,3) #10除以3 (3, 1) #返回(商,余数)
- id() 查内存地址
- sorted() 排序,默认由小到大
#列表排序,和sort功能一致 >>> l = list(range(10)) >>> l[4] = 99 >>> l [0, 1, 2, 3, 99, 5, 6, 7, 8, 9] >>> sorted(l) [0, 1, 2, 3, 5, 6, 7, 8, 9, 99] >>> l [0, 1, 2, 3, 99, 5, 6, 7, 8, 9] >>> l.sort() >>> l [0, 1, 2, 3, 5, 6, 7, 8, 9, 99] #字典排序 >>> d = {} >>> for i in range(20): ... d[i] = i-50 ... >>> d #字典本身无序 {0: -50, 1: -49, 2: -48, 3: -47, 4: -46, 5: -45, 6: -44, 7: -43, 8: -42, 9: -41, 10: -40, 11: -39, 12: -38, 13: -37, 14: -36, 15: -35, 16: -34, 17: -33, 18: -32, 19: -31} >>> d.items() #生成元组同样无序 dict_items([(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41), (10, -40), (11, -39), (12, -38), (13, -37), (14, -36), (15, -35), (16, -34), (17, -33), (18, -32), (19, -31)]) >>> sorted(d.items()) #默认从小到大排序 [(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41), (10, -40), (11, -39), (12, -38), (13, -37), (14, -36), (15, -35), (16, -34), (17, -33), (18, -32), (19, -31)] >>> sorted(d.items(),key= lambda x:x[1]) #按照value值从小到大排序 [(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41), (10, -40), (11, -39), (12, -38), (13, -37), (14, -36), (15, -35), (16, -34), (17, -33), (18, -32), (19, -31)] >>> d[0] = 399 >>> sorted(d.items(),key=lambda x:x[1]) #按照value值从小到大排序 [(1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41), (10, -40), (11, -39), (12, -38), (13, -37), (14, -36), (15, -35), (16, -34), (17, -33), (18, -32), (19, -31), (0, 399)] >>> sorted(d.items(),key=lambda x:x[1],reverse=True) #按照value值从大到小排序 [(0, 399), (19, -31), (18, -32), (17, -33), (16, -34), (15, -35), (14, -36), (13, -37), (12, -38), (11, -39), (10, -40), (9, -41), (8, -42), (7, -43), (6, -44), (5, -45), (4, -46), (3, -47), (2, -48), (1, -49)]
- reversed() 和sorted()一样,不过是默认由大到小
- ascii() 返回unico编码
>>> s = 'abcd路飞' >>> s 'abcd路飞' >>> ascii(s) #返回s的Unicode编码 "'abcd\\u8def\\u98de'"
- enumerate() 枚举,返回索引
- input() 输入
- oct() 转成八进制
- bin() 转成二进制
- eval() 按解释器的规则把单行字符串转成代码运行
#将字符串转换成公式进行运算 >>> s = '1+3/2' >>> s '1+3/2' >>> eval(s) 2.5 #执行单行代码 >>> eval('print("hello world")') hello world #不能执行多行代码 >>> code = ''' ... if 3>5 : ... print('3 is bigger than 5') ... else: ... print('dddd') ... ''' >>> code "\nif 3>5 :\n\tprint('3 is bigger than 5')\nelse:\n\tprint('dddd')\n\n\n" >>> eval(code) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 2 if 3>5 : ^ SyntaxError: invalid syntax
- exec() 能运行多行代码,但是没有返回值
#exec()能运行多行代码但无返回值 >>> code = ''' ... def foo(): ... print('run foo') ... return 1234 ... foo() ... ''' >>> res = exec(code) run foo >>> print('res',res) res None #运行单行代码与eval()对比 >> res1 = eval("1+3+3") >>> res2 = exec("1+3+3") >>> print('res',res1,res2) res 7 None
- int() 转换成整数类型
- open() 打开文件open(file='', mode='',encoding='')
- str() 转换成字符串类型
- bool() 判断True or False,只有0是False
- ord() 返回字符串在ASCII码里的值
>>> ord('a') 97
- chr() 返回ASCII码值对应的字符串
>>> chr(97) 'a'
- sum()
>>> a = [1,4,5,-1,3,0] >>> a [1, 4, 5, -1, 3, 0] >>> sum(a) #将列表中所有元素加起来求和 12
- bytearray()
- 一般用于修改长字符串,短字符串可改成列表然后进行修改。
- 可将字符串在原地址上修改,但字符串中修改的个别元素的地址会发生变化。
>>> s = 'abcd路飞' >>> id(s) 1496733953552 >>> s = s.encode('gbk') >>> s b'abcd\xc2\xb7\xb7\xc9' >>> s = bytearray(s) #字符串变成bytearray之后能修改 >>> s bytearray(b'abcd\xc2\xb7\xb7\xc9') >>> s[4] 194 >>> s[4] = 233 >>> s bytearray(b'abcd\xe9\xb7\xb7\xc9') >>> s = s.decode('gbk') >>> s 'abcd榉飞' >>> id(s) #在原地址上修改 1496733953552
- map()
>>> map(lambda x:x*x,[1,2,3,4,5]) <map object at 0x0000015C7C561080> >>> list(map(lambda x:x*x,[1,2,3,4,5])) [1, 4, 9, 16, 25]
- filter() 过滤
>>> filter(lambda x:x>3,[1,2,3,4,5]) #筛选出满足lambda条件的元素 <filter object at 0x0000015C7C561048> >>> list(filter(lambda x:x>3,[1,2,3,4,5])) [4, 5]
- reduce()
>>> import functools >>> functools.reduce(lambda x,y:x+y,[1,2,3,4,5,6,7,8]) #求和 36 >>> functools.reduce(lambda x,y:x*y,[1,2,3,4,5,6,7,8]) #求乘积 40320 >>> functools.reduce(lambda x,y:x+y,[1,2,3,4,5,6,7,8],3) #求和加上最后一项 39
- pow() 求次方 pow(a, b) = a**b
- bytes() 换成byte类型
- float() 换成浮点类型
- print() 打印 print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) flush以后会用到,这里先不讲
>>> s = 'hey, my name is alex\n, from Shanghai' >>> print(s) hey, my name is alex , from Shanghai >>> print(s,end='.') hey, my name is alex , from Shanghai.>>> #在最后会默认加一个\n ... >>> print(s,end='|') #end是以什么结尾 hey, my name is alex , from Shanghai|>>> >>> print('haifeng','gangniang',sep='->') #sep是以什么连接两个字符串 haifeng->gangniang
#写入文件 msg = '又回到最初的原点' f = open('print_tofile.txt', 'w') print(msg, '记忆中你青涩的脸', sep='|', end='.', file=f)#不会在最后自带换行,重复本行命令,可连着写入
- tuple() 变成元组
- callable() 判断是否可调用
>>> def f(): ... pass ... >>> callable(f) #带(),即是函数,就可调用,其余不可调用 True >>> lis = [1,2,3] >>> callable(lis) False
- format() 格式化
- len() 获取长度
- type() 类型
- frozenset() 冷冻的集合,即为不可变的集合
>>> s = {1,2,3,4,5} >>> s.discard(1) >>> s {2, 3, 4, 5} >>> s = frozenset(s) >>> s.discard(3) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'frozenset' object has no attribute 'discard'
- list() 列表
- range() 循环
- repr() 把变量值显示成字符串形式
>>> s frozenset({2, 3, 4, 5}) >>> repr(s) 'frozenset({2, 3, 4, 5})'
- zip() 将两个列表元素一一对应生成元组,无对应元素的多余部分被舍弃
>>> a = [1,2,3,4,5] >>> b = ['a','b','c'] >>> a [1, 2, 3, 4, 5] >>> b ['a', 'b', 'c'] >>> zip(a,b) <zip object at 0x000002C1118C4FC8> >>> list(zip(a,b)) [(1, 'a'), (2, 'b'), (3, 'c')]
- complex() 把数字变成复数
>>> complex(3,5)
(3+5j)
- round() 保留几位小数,默认不保留小数部分
>>> round(1.234567) 1 >>> round(1.234567,2) 1.23
- hash() 把字符串变成数字
#只要不重启,数字不会重复 >>> hash('abcd') 6166213067681790707 >>> hash('abcd') 6166213067681790707
- set() 把列表变成集合
>>> set([1,2,3,4])
{1, 2, 3, 4}
后面讲模块会讲到:_import_()
后面面向对象再讲:next() object() staticmethod() isinstance() property() classmethod()
delattr() hasattr() getattr() setattr() 四剑客放在后面一起讲
memoryview() 基本用不到,用于大数据处理
compile() 编译代码用,现在用不到,讲模板引擎的时候可能会用到