跳转至

内置函数

>>>  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', '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']

内置函数部分解析

  • help()

查看内置模块的使用帮助

  • abs(x)

求绝对值

  • round(x, n)
# 四舍五入
round(1.237, 2)  # 1.24
  • range(start, stop, step)
# 生成整数列表的迭代器,需要使用list()转换为列表
# start默认为0,step默认为1,生成的列表不包含stop
list(range(5))  # 等价于range(0,5,1),[0,1,2,3,4]
list(range(0))  # []
list(range(0,-5,-1))  # [0,-1,-2,-3,-4]

range()random()、切片等都不包含右边

  • slice()reversed()zip()
_str = "abc"
_tuple = (1,2,3)
_list = [1,2,3]


# slice()
_list[slice(0,2)]  # 等价于:_list[0:2]


# reversed()
# 反转后得到一个迭代器
r = reversed(x)  # <reversed object at 0x105acab50>
[i for i in r]  # [3,2,1]


# zip()
r = zip(_tuple,_list)  # <zip object at 0x10777b550>
[i for i in r]  # [(1, 1), (2, 2), (3, 3)]
  • enumerate()
lst = ['one','two','three','four','five']
[i for i in enumerate(lst)]  # [(0, 'one'), (1, 'two'), (2, 'three'), (3, 'four'), (4, 'five')]
[i for i in enumerate(lst, 1)]  # 标号从1开始
  • all()any()
all(Iterable)  # Iterable元素中全是True,则返回True
any(Iterable)  # Iterable元素中有一个是True,则返回True
  • input()print()
r = input("请输入...")  # 返回str类型


# 注意:
# 1. 同时输出多个值,默认空格分隔,可以自定义seq变量控制
# 2. 输出结束会末尾会自动加一个换行,可以自定义end变量控制
print(123 seq="", end="\n")

# pprint(pretty print)可以输出格式化的数据
from pprint import pprint
pprint(data)
  • eval()exec()compile()

eval(object, [globals])用于字符串形式的执行单个表达式,不能做赋值循环等操作,返回表达式的结果

y = eval("1+2")  # y=3

exec(object, [globals])用于执行字符串形式的语句,返回None

y = exec("x=1+2")  # y=None, x=3

compile(string, "", mode)可以将字符串编译为eval()和exec()可执行的格式,https://segmentfault.com/q/1010000017171114

我理解通常代码很复杂或为了复用时才需要compile预先编译,不然并没有什么卵用,直接使用eval/exec即可

cmd = compile("1+2", "", mode="eval")
eval(cmd)  # 3

这几个函数一定要慎用,可能会因为代码注入带来安全隐患

比如:eval("__import__('os').system('rm -rf *')")

如果字符串中是标准的python数据类型,可以用ast.literal_eval()方法替代,它会判断内容是否为合法的python类型,为否则会报错。

import ast

_str = "_dcit"
# 如果_str="faker.name()"这种非合法python类型,则会报错
# 另外_str=""也会报错
_dcit = ast.literal_eval(_str)
  • filter(判断函数, iterable)

序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

  • map(func, iterable)
def square(x):
    return x ** 2

map(square, [1,2,3,4,5])  # 计算列表各个元素的平方,返回迭代器:<map object at 0x100d3d550>     

# [1, 4, 9, 16, 25]
list(map(square, [1,2,3,4,5]))  # 使用list()转换为列表
list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))  # 使用lambda匿名函数