python常用内建函数

简介: 内建函数是python解释器内置的函数,由cpython执行的c语言编写的函数,在加载速度上优于开发者自定义的函数,上一篇将python常用内建属性说了《python常用内建属性大全》,本篇说常用的内建函数。

内建函数是python解释器内置的函数,由cpython执行的c语言编写的函数,在加载速度上优于开发者自定义的函数,上一篇将python常用内建属性说了《python常用内建属性大全》,本篇说常用的内建函数。

当打开python解释器后输入dir(__builtins__)即可列举出python所有的内建函数:

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'Blocki
ngIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError
', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'Conne
ctionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentErro
r', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPoint
Error', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarni
ng', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError',
'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundEr
ror', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplement
edError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionEr
ror', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning
', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'Syn
taxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutErr
or', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEnc
odeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarni
ng', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_clas
s__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package
__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'byt
earray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyr
ight', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec
', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasa
ttr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', '
iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'n
ext', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range
', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmeth
od', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']


map函数

map函数对指定序列映射到指定函数

map(function, sequence[, sequence, ...]) -> list

对序列中每个元素调用function函数,返回列表结果集的map对象

#函数需要一个参数
list(map(lambda x: x*x, [123]))
#结果为:[1, 4, 9]

#函数需要两个参数
list(map(lambda x, y: x+y, [123], [456]))
#结果为:[5, 7, 9]


def f1( x, y ):  
    return (x,y)

l1 = [ 0123456 ]  
l2 = [ 'Sun''M''T''W''T''F''S' ]
a = map( f1, l1, l2 ) 
print(list(a))
#结果为:[(0, 'Sun'), (1, 'M'), (2, 'T'), (3, 'W'), (4, 'T'), (5, 'F'), (6, 'S')]


filter函数

filter函数会对指定序列按照规则执行过滤操作

filter(...)
    filter(function or None, sequence) -> list, tuple, or string

    Return those items of sequence for which function(item) is true.  If
    function is None, return the items that are true.  If sequence is a tuple
    or stringreturn the same type, else return a list.
  • function:接受一个参数,返回布尔值True或False

  • sequence:序列可以是str,tuple,list

filter函数会对序列参数sequence中的每个元素调用function函数,最后返回的结果包含调用结果为True的filter对象。

与map不同的是map是返回return的结果,而filter是更具return True条件返回传入的参数,一个是加工一个是过滤。

返回值的类型和参数sequence的类型相同

list(filter(lambda x: x%2, [1234]))
[13]

filter(None"she")
'she'

reduce函数

reduce函数,reduce函数会对参数序列中元素进行累积

reduce(...)
    reduce(function, sequence[, initial]) -> value

    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [12345]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.
  • function:该函数有两个参数

  • sequence:序列可以是str,tuple,list

  • initial:固定初始值

reduce依次从sequence中取一个元素,和上一次调用function的结果做参数再次调用function。 第一次调用function时,如果提供initial参数,会以sequence中的第一个元素和initial 作为参数调用function,否则会以序列sequence中的前两个元素做参数调用function。 注意function函数不能为None。

空间里移除了, 它现在被放置在fucntools模块里用的话要先引入: from functools import reduce

reduce(lambda x, y: x+y, [1,2,3,4])
10

reduce(lambda x, y: x+y, [1,2,3,4], 5)
15

reduce(lambda x, y: x+y, ['aa''bb''cc'], 'dd')
'ddaabbcc'



相关文章
|
1天前
|
开发者 Python
Python入门:8.Python中的函数
### 引言 在编写程序时,函数是一种强大的工具。它们可以将代码逻辑模块化,减少重复代码的编写,并提高程序的可读性和可维护性。无论是初学者还是资深开发者,深入理解函数的使用和设计都是编写高质量代码的基础。本文将从基础概念开始,逐步讲解 Python 中的函数及其高级特性。
Python入门:8.Python中的函数
|
1月前
|
存储 人工智能 Python
[oeasy]python061_如何接收输入_input函数_字符串_str_容器_ 输入输出
本文介绍了Python中如何使用`input()`函数接收用户输入。`input()`函数可以从标准输入流获取字符串,并将其赋值给变量。通过键盘输入的值可以实时赋予变量,实现动态输入。为了更好地理解其用法,文中通过实例演示了如何接收用户输入并存储在变量中,还介绍了`input()`函数的参数`prompt`,用于提供输入提示信息。最后总结了`input()`函数的核心功能及其应用场景。更多内容可参考蓝桥、GitHub和Gitee上的相关教程。
16 0
|
1月前
|
Python
[oeasy]python057_如何删除print函数_dunder_builtins_系统内建模块
本文介绍了如何删除Python中的`print`函数,并探讨了系统内建模块`__builtins__`的作用。主要内容包括: 1. **回忆上次内容**:上次提到使用下划线避免命名冲突。 2. **双下划线变量**:解释了双下划线(如`__name__`、`__doc__`、`__builtins__`)是系统定义的标识符,具有特殊含义。
32 3
|
1月前
|
JSON 监控 安全
深入理解 Python 的 eval() 函数与空全局字典 {}
`eval()` 函数在 Python 中能将字符串解析为代码并执行,但伴随安全风险,尤其在处理不受信任的输入时。传递空全局字典 {} 可限制其访问内置对象,但仍存隐患。建议通过限制函数和变量、使用沙箱环境、避免复杂表达式、验证输入等提高安全性。更推荐使用 `ast.literal_eval()`、自定义解析器或 JSON 解析等替代方案,以确保代码安全性和可靠性。
45 2
|
2月前
|
数据可视化 DataX Python
Seaborn 教程-绘图函数
Seaborn 教程-绘图函数
87 8
|
2月前
|
Python
Python中的函数是**一种命名的代码块,用于执行特定任务或计算
Python中的函数是**一种命名的代码块,用于执行特定任务或计算
64 18
|
2月前
|
Python
Python中的函数
Python中的函数
62 8
|
3月前
|
搜索推荐 Python
利用Python内置函数实现的冒泡排序算法
在上述代码中,`bubble_sort` 函数接受一个列表 `arr` 作为输入。通过两层循环,外层循环控制排序的轮数,内层循环用于比较相邻的元素并进行交换。如果前一个元素大于后一个元素,就将它们交换位置。
155 67
|
3月前
|
监控 测试技术 数据库
Python中的装饰器:解锁函数增强的魔法####
本文深入探讨了Python语言中一个既强大又灵活的特性——装饰器(Decorator),它以一种优雅的方式实现了函数功能的扩展与增强。不同于传统的代码复用机制,装饰器通过高阶函数的形式,为开发者提供了在不修改原函数源代码的前提下,动态添加新功能的能力。我们将从装饰器的基本概念入手,逐步解析其工作原理,并通过一系列实例展示如何利用装饰器进行日志记录、性能测试、事务处理等常见任务,最终揭示装饰器在提升代码可读性、维护性和功能性方面的独特价值。 ####
|
3月前
|
中间件 Docker Python
【Azure Function】FTP上传了Python Function文件后,无法在门户页面加载函数的问题
通过FTP上传Python Function至Azure云后,出现函数列表无法加载的问题。经排查,发现是由于`requirements.txt`中的依赖包未被正确安装。解决方法为:在本地安装依赖包到`.python_packages/lib/site-packages`目录,再将该目录内容上传至云上的`wwwroot`目录,并重启应用。最终成功加载函数列表。

热门文章

最新文章

推荐镜像

更多