当前位置: 首页 > ai >正文

Python初学者笔记第十三期 -- (常用内置函数)

第22节课 常用内置函数

回顾一下之前见到过的内置函数

  • 输入输出类:input、print、eval、map
  • 数据类型转换类:int、float、bool、str、list、tuple、set、dict
  • 其他:bin、oct、hex、ord、chr、max、min、sum、pow、abs、id、type、exit、quit、sorted、help

dir(object):主要用于查看对象的所有属性和方法,能够帮助使用者多加了解对象的功能。

  • dir() 如果不传入参数的话,它会返回当前本地作用域中的名称列表(当先作用域中定义的变量、函数、类等名称)【列表顺序仅仅按照首字母的ASCII顺序打印,与使用频率重要性无关】
def show():pass
num = 10
circle = 3.14
print(dir())
"""
['__annotations__', '__builtins__', '__cached__', 
'__doc__', '__file__', '__loader__', 
'__name__', '__package__', '__spec__', 
'circle', 'num', 'show']
"""
  • dir(object) 传入一个对象作为参数时,它会返回该对象的所有属性和方法的名称-列表形式。
arr = [1,2,3,4]
s = {1,2,3,4}
print(dir(arr))
print(dir(s))
"""
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
['__and__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
"""
  • 特殊属性和方法:返回的列表中可能包含以下双下划线开头的名称,这些是Python的特殊属性和方法。
# 查看所有Python的内置函数/内置数据
count = 0
for item in dir(__builtins__):print(item, end = "\t")count += 1if count % 10 == 0:print()
"""
ArithmeticError	AssertionError	AttributeError	BaseException	BaseExceptionGroup	BlockingIOError	BrokenPipeError	BufferError	BytesWarning	ChildProcessError	
ConnectionAbortedError	ConnectionError	ConnectionRefusedError	ConnectionResetError	DeprecationWarning	EOFError	Ellipsis	EncodingWarning	EnvironmentError	Exception	
ExceptionGroup	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	aiter	all	anext	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	
"""

round(number, ndigits):用于对数字进行四舍五入操作

  • number:必须要填写的内容,对哪个数字进行四舍五入,可以是整数也可以是小数
  • ndigits:可选参数,是一个整数,用来指定要保留的小数位数,如果不写则默认为0
print(round(5))
print(round(3.2))
print(round(3.8))
print(round(3.1415926, 3))

额外的,对于处理结尾为5的数字时,采用的是“银行家舍入法”,会将其舍入到最接近的偶数

print(round(2.5)) # 2
print(round(3.5)) # 4	
print(round(4.5)) # 4
print(round(5.5)) # 6

ndigits也可以是负数,将整数部分进行四舍五入

print(round(12345, -3)) # 12000

all(iterable):用于判断可迭代对象中的所有元素是否都为真

  • iterable:必填,可迭代对象(列表、字符串、元组、集合、字典)

  • 什么是假:False、0、0.0、“”、[]、{}、()、None

arr = [1, 3.14, [1,2,3],{1,2,3}]
print(all(arr)) # True
arr = [1, 3.14, [],{1,2,3}]
print(all(arr)) # False
# 针对字典的操作 主要看键 不管值
dic = {"name":"张三","age":18, 0:666}
print(all(dic)) # False

any(iterable):用于判断可迭代对象中是都至少包含一个元素为真

filter(function, iterable):用于过滤可迭代对象中的元素,返回的是一个迭代器

  • function:用于筛选元素的函数,必须返回一个布尔类型的值
arr = [1,2,3,4,5,6,7,8,9,10]
arr1 = [item for item in arr if item % 2 == 0]
print(arr1)# 过滤函数对某一个元素进行具体的操作
def is_even(number):return number % 2 == 0
arr2 = list(filter(is_even, arr))
print(arr2)

如果不传入过滤函数时(传入None参数),则自动默认将可迭代对象中的假值进行过滤。

arr = [0,0.0,[],"",1,2,3]
lst = list(filter(None,arr))
print(lst)
  • filter返回的是一个迭代器对象。这意味着它不会立即对可迭代对象进行遍历和筛选,而是在需要时逐个区生成每一个满足条件的元素。如果像一次性获取所有元素的话,可以利用list()、tuple()之类序列函数来获取。
  • 相对而言,迭代器的内存效率会更高,在处理大批量数据时,不会直接把所有元素进行生成,而是根据需求自动来进行筛选和计算。

next(Iterator, default):主要用于获取迭代器的下一个元素。

  • Iterator :迭代器(实现了__next__方法的对象)
  • default:可选参数,当迭代器耗尽时,既没有更多元素时,返回这个默认值(结束标记),如果不写则遍历结束时会报错。
  • 当迭代器遍历完毕后,则不能再重复利用
arr = [1,2,3,4,5,6,7,8,9,10]def is_even(number):return number % 2 == 0
it = filter(is_even, arr)
print(next(it)) # 2 每调用一次next 生成一个元素
print(next(it)) # 4arr = [1,2,3,4]
# 获取可迭代对象的迭代器
it = iter(arr)
print(it)
print(type(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it)) # 此时it工作已经结束了 不能再被复用
"""
1
2
3
4
Traceback (most recent call last):File "C:\Users\HENG\Desktop\PyDay20\Demo.py", line 10, in <module>print(next(it))^^^^^^^^
StopIteration
"""arr = [1,2,3,4]
# 获取可迭代对象的迭代器
it = iter(arr)
while True:num = next(it, -1)if num == -1:breakprint(num)dic = {0:1,1:2,2:3,3:4,4:5}
it = iter(dic.keys())
print(next(it))
print(next(it))

iter(iterable) / iter(callable, sentinel)

  • iter(iterable):获取某一个可迭代对象的迭代器
arr = [1,2,3,4]
# 获取可迭代对象的迭代器
it = iter(arr)
while True:num = next(it, -1)if num == -1:breakprint(num)arr = [1,2,3,4]
# 获取可迭代对象的迭代器
it = iter(arr)
for number in it:print(number)
  • iter(callable, sentinel):可以自定义一个迭代函数callable,来动态生成元素;sentinel标记值,当迭代到sentinel这个值时(返回值),则停止迭代。
num = 1
def get_number():global num # 全局result = num # 局部num += 1return result
it = iter(get_number, 4)
for number in it:print(number)

map(function, iterable,…):用于可迭代对象中的每一个元素应用指定的函数,并返回一个迭代器。

  • iterable,...:可以传入多个可迭代对象的,对应的function也必须能够承接这么多的对象。
  • 多个迭代对象的长度尽量一致,如果长度不一致,以最短为主。
def square(x):return x ** 2
arr = [1,2,3,4]
it = map(square, arr)
for num in it:print(num)def square(x, y):return x + y
arr1 = [1,2,3,4]
arr2 = [5,6,7,8]
it = map(square, arr1, arr2)
for num in it:print(num)

reversed(seq):用于返回一个反向迭代器,逆序遍历,不对原数据做改变

  • seq:必填参数,代表一个序列。
arr = [1,2,3,4,5]
# 反向的迭代器
it = reversed(arr)
for num in it:print(num)

zip(*iterables):用于将多个可迭代对象中对应位置的元素打包成一个个元组,然后返回这些元组组成的迭代器。以最短为主。

arr1 = [1,2,3,4,5]
arr2 = ['A','B','C','D','E']
arr3 = ['a','b','c','d','e']
it = zip(arr1, arr2, arr3)
for item in it:print(item)
arr1 = [1,2,3,4,5]
arr2 = ['A','B','C','D','E']
arr3 = ['a','b','c','d','e']
it = zip(arr1, arr2, arr3)
for item in it:print(item)
it = zip(arr1, arr2, arr3)
for a,b,c in it:print(a,b,c)

可以使用*对zip函数的结果进行解压缩,结果还是元组对象。

paris = [
(1, 'A', 'a'),
(2, 'B', 'b'),
(3, 'C', 'c'),
(4, 'D', 'd'),
(5, 'E', 'e')
]
print(paris)
lst1, lst2, lst3 = zip(*paris)
print(lst1)
print(lst2)
print(lst3)

其他暂时还用不到的内置函数,之后或课外学习:

函数说明
aiter()从异步对象中获取对应的异步迭代器
anext()从异步迭代器中获取下一个数据
ascii()判断参数数据是否一个标准的可打印ascii字符
breakpoint()间接调用系统中的钩子函数进行代码调试
bytearray()Python中用来创建字节数组的函数
bytes()构建字节序列的,类似bytearray、
callable()判断参数数据是否可以被执行,经常用于编写后门木马时探测目标数据
classmethod面向对象中-用于声明类方法的装饰器函数
compile()用于将字符串数据编译成可执行脚本,提供给exec()或者eval()函数调用执行
complex()数据处理中用于复数处理的类型
copyright()python内置的 版本信息 内置函数
credits()python内置的 贡献者信息 内置函数
delattr()面向对象中-用于删除对象属性的函数
divmod()用于直接查询整除数据和取余数据的函数
exec()类似eval(),也可以将字符串转化成表达式进行执行
format()用于数据格式化的函数
frozenset()用于将序列数据进行乱序处理的函数
getattr()面向对象中-用于获取对象中的属性的函数
globals()用于获取当前作用域中所有全局变量的函数
locals()用于获取当前作用域中所有局部变量的函数,类似vars()
vars()用于获取当前作用域中所有局部变量的函数,类似vars()
hasattr()面向对象中-用于判断对象中是否包含某个属性的函数
hash()用于获取参数数据的hash值的函数,底层函数
isinstance()面向对象中-身份运算符,判断某个对象是否属于某种类型,如张三是个人吗?
issubclass()面向对象中-身份运算符,判断某个小类型是否属于某个大类型,如男人是人吗?
license()python中的版本信息
memoryview()用于获取参数数据的内存数据
object()python中的顶级对象类型
open()内置的用于打开并操作系统文件的函数
property()面向对象-用于对象属性封装
repr()面向对象-用于输出对象
setattr()面向对象-用于给对象设置属性的函数
slice()用于阶段拆分字符串的内置函数
staticmethod()面向对象-用于声明静态方法的装饰器函数
super()面向对象-用于表示继承关系中父类型的关键字
http://www.xdnf.cn/news/15392.html

相关文章:

  • 【鸿蒙HarmonyOS】鸿蒙app开发入门到实战教程(二):封装自定义可复用组件
  • 深入解析环境变量:从基础概念到系统级应用
  • kdump生成转储文件调试内核崩溃、死机
  • Java 栈和队列
  • linux 系统依赖包查询命令汇总
  • IPM31主板E3300usb键盘鼠标安装成功Sata接口硬盘IDE模式server2003-nt-5.2.3790
  • python 的包管理工具pip poetry、conda 和 pipenv 使用和安装
  • C 语言部分操作符详解 -- 进制转换,原码、反码、补码,位操作符,逗号表达式,操作符的优先级和结合性,整型提升,算术转换
  • 2025年小目标检测分享:从无人机视角到微观缺陷的创新模型
  • 【PTA数据结构 | C语言版】二叉树前序序列化
  • Python初学者笔记第十二期 -- (集合与字典编程练习题)
  • Vim多列操作指南
  • TCP可靠性设计的核心机制与底层逻辑
  • next.js 登录认证:使用 github 账号授权登录。
  • uni-app+vue3 来说一说前端遇到跨域的解决方案
  • 全连接神经网络
  • 10分钟搞定!Chatbox+本地知识库=你的私人语音导师:企业级全栈实现指南
  • 自动微分模块
  • JAR 包冲突排雷指南:原理、现象与 Maven 一站式解决
  • 机载激光雷达目标识别:从点云到凝视成像的算法全景
  • Datawhale AI夏令营——用户新增预测挑战赛
  • xss-lab靶场通关
  • 苦练Python第18天:Python异常处理锦囊
  • 从 JSON 到 Python 对象:一次通透的序列化与反序列化之旅
  • 云原生技术与应用-Containerd容器技术详解
  • Android系统的问题分析笔记 - Android上的调试方式 bugreport
  • RAG索引流程中的文档解析:工业级实践方案与最佳实践
  • iOS —— 网易云仿写
  • 大数据系列之:通过trino查询hive表
  • 直播推流技术底层逻辑详解与私有化实现方案-以rmtp rtc hls为例-优雅草卓伊凡