08-27-周三_17-09-29
This commit is contained in:
672
Python/Python面向函数/内置函数与匿名函数.md
Normal file
672
Python/Python面向函数/内置函数与匿名函数.md
Normal file
@@ -0,0 +1,672 @@
|
||||
# 内置函数
|
||||
|
||||
截止到python版本3.9.22,python一共为我们提供了**69个内置函数。**
|
||||
|
||||
https://docs.python.org/zh-cn/3.9/library/functions.html
|
||||
|
||||
## 作用域相关
|
||||
|
||||
### `locals()`
|
||||
函数会以字典的类型返回当前位置的全部局部变量。
|
||||
|
||||
### `globals()`
|
||||
函数以字典的类型返回全部全局变量。
|
||||
|
||||
**示例**
|
||||
```python
|
||||
a = 1
|
||||
b = 2
|
||||
|
||||
print(locals())
|
||||
print(globals())
|
||||
|
||||
# 这两个一样,因为是在全局执行的
|
||||
|
||||
def func(argv):
|
||||
c = 2
|
||||
print(locals())
|
||||
print(globals())
|
||||
|
||||
func(3)
|
||||
```
|
||||
|
||||
## 字符串类型代码执行
|
||||
|
||||
### `eval()`
|
||||
|
||||
计算指定表达式的值,并返回最终结果
|
||||
|
||||
```python
|
||||
ret = eval('2 + 2')
|
||||
print(ret)
|
||||
|
||||
n = 20
|
||||
ret = eval('n + 23')
|
||||
print(ret)
|
||||
|
||||
eval('print("Hello world")')
|
||||
```
|
||||
|
||||
### `exec()`
|
||||
|
||||
执行字符串类型的代码
|
||||
|
||||
```python
|
||||
s = '''
|
||||
for i in range(5):
|
||||
print(i)
|
||||
'''
|
||||
|
||||
exec(s)
|
||||
|
||||
```
|
||||
|
||||
### `compile()`
|
||||
|
||||
用于将源代码编译成字节码,从而可以在后续执行中使用。这个函数的主要作用是将字符串形式的代码转换为可以通过 `exec()` 或 `eval()` 执行的代码对象。
|
||||
|
||||
**语法**
|
||||
|
||||
```python
|
||||
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
|
||||
```
|
||||
|
||||
**参数**
|
||||
|
||||
- **source**:要编译的源代码,可以是字符串或 AST(抽象语法树)对象。
|
||||
- **filename**:表示代码的文件名(通常为字符串),用于错误消息的显示。可以是任意字符串。
|
||||
- **mode**:指定编译模式
|
||||
- `'exec'` :用于编译多条语句(如模块或函数)。
|
||||
- `'eval'` :用于编译单个表达式。
|
||||
- `'single'` :用于编译单个交互式语句。
|
||||
|
||||
**返回值**
|
||||
|
||||
返回一个代码对象,可以使用 `exec()` 或 `eval()` 执行
|
||||
|
||||
**示例**
|
||||
|
||||
```python
|
||||
# 流程语句使用exec
|
||||
code1 = 'for i in range(5): print(i)'
|
||||
compile1 = compile(code1,'','exec')
|
||||
exec(compile1)
|
||||
|
||||
# 简单求值表达式用eval
|
||||
code2 = '1 + 2 + 3'
|
||||
compile2 = compile(code2,'','eval')
|
||||
eval(compile2)
|
||||
|
||||
# 交互语句用single
|
||||
code3 = 'name = input("please input you name: ")'
|
||||
compile3 = compile(code3,'','single')
|
||||
|
||||
exec(compile3)
|
||||
print(name)
|
||||
```
|
||||
|
||||
有返回值的字符串形式的代码用 eval,没有返回值的字符串形式的代码用 exec,一般不用 compile。
|
||||
|
||||
## 输入/输出相关
|
||||
|
||||
### `input()`
|
||||
|
||||
函数接受一个标准输入数据,返回为 string 类型。
|
||||
|
||||
### `print()`
|
||||
|
||||
打印输出。
|
||||
|
||||
```python
|
||||
''' 源码分析
|
||||
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
|
||||
"""
|
||||
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
|
||||
file: 默认是输出到屏幕,如果设置为文件句柄,输出到文件
|
||||
sep: 打印多个值之间的分隔符,默认为空格
|
||||
end: 每一次打印的结尾,默认为换行符
|
||||
flush: 立即把内容输出到流文件,不作缓存
|
||||
"""
|
||||
'''
|
||||
|
||||
print(11,22,33,sep='*')
|
||||
print(11,22,33,end='')
|
||||
print(44,55)
|
||||
|
||||
with open('log','w',encoding='utf-8') as f:
|
||||
print('写入文件',file=f,flush=True)
|
||||
```
|
||||
|
||||
## 内存相关
|
||||
|
||||
### `hash()`
|
||||
|
||||
获取一个对象(可哈希对象:int,str,bool,tuple)的哈希值。
|
||||
|
||||
```python
|
||||
print(hash(12322))
|
||||
print(hash('123'))
|
||||
print(hash('arg'))
|
||||
print(hash('aaron'))
|
||||
print(hash(True))
|
||||
print(hash(False))
|
||||
print(hash((1,2,3)))
|
||||
|
||||
```
|
||||
|
||||
### `id()`
|
||||
|
||||
用于获取对象的内存地址
|
||||
|
||||
```python
|
||||
print(id('abc'))
|
||||
print(id('123'))
|
||||
|
||||
```
|
||||
|
||||
## 文件操作相关
|
||||
|
||||
### `open()`
|
||||
|
||||
用于打开一个文件,创建一个 file 对象
|
||||
|
||||
### `read()`
|
||||
|
||||
通过文件对象调用,读取文件的内容
|
||||
|
||||
### `write()`
|
||||
|
||||
文件文件对象调用,往文件里下入内容
|
||||
|
||||
.......
|
||||
|
||||
## 帮助文档
|
||||
|
||||
### `help()`
|
||||
|
||||
函数用于查看函数或模块用途的详细说明。
|
||||
|
||||
```python
|
||||
print(help(print))
|
||||
|
||||
#结果
|
||||
print(...)
|
||||
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
|
||||
|
||||
Prints the values to a stream, or to sys.stdout by default.
|
||||
Optional keyword arguments:
|
||||
file: a file-like object (stream); defaults to the current sys.stdout.
|
||||
sep: string inserted between values, default a space.
|
||||
end: string appended after the last value, default a newline.
|
||||
flush: whether to forcibly flush the stream.
|
||||
```
|
||||
|
||||
## 调用相关
|
||||
|
||||
### `callable()`
|
||||
|
||||
用于检查一个对象是否是可调用的。如果返回 True,object 仍然可能调用失败;但如果返回 False,调用对象 ojbect 绝对不会成功。
|
||||
|
||||
```python
|
||||
print(callable(0))
|
||||
print(callable('hello'))
|
||||
|
||||
# 自定义函数
|
||||
def demo1(a, b):
|
||||
return a + b
|
||||
print(callable(demo1))
|
||||
|
||||
# 自定义类
|
||||
class Demo2:
|
||||
def test1(self):
|
||||
return 0
|
||||
|
||||
print(callable(Demo2))
|
||||
|
||||
# 实例化对象
|
||||
a = Demo2()
|
||||
print(callable(a))
|
||||
|
||||
```
|
||||
|
||||
## 查看内置属性
|
||||
|
||||
### `dir()`
|
||||
函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法 `__dir__()` ,该方法将被调用。如果参数不包含 `__dir__()` ,该方法将最大限度地收集参数信息。
|
||||
|
||||
```python
|
||||
import time
|
||||
print(dir(time)) # 查看某个模块的属性和方法
|
||||
|
||||
print(dir([])) # 查看列表的属性和方法
|
||||
```
|
||||
|
||||
## 迭代器生成器相关
|
||||
|
||||
### `range()`
|
||||
|
||||
函数可创建一个整数对象,一般用在 for 循环中。
|
||||
|
||||
### `next()`
|
||||
|
||||
内部实际使用了 `__next__` 方法,返回迭代器的下一个项目。
|
||||
|
||||
### `iter()`
|
||||
|
||||
函数用来生成迭代器(通过一个可迭代对象生成迭代器)。
|
||||
|
||||
```python
|
||||
from collections import Iterator
|
||||
|
||||
# 首先获得Iterator对象:
|
||||
l = [1,2,3,4]
|
||||
l1 = iter(l)
|
||||
|
||||
print(isinstance(l1,Iterable))
|
||||
print(isinstance(l1,Iterator))
|
||||
|
||||
# 循环
|
||||
while True:
|
||||
try:
|
||||
# 获得下一个值
|
||||
x = next(l1)
|
||||
print(x)
|
||||
except StopIteration: # 遇到StopIteration就退出循环
|
||||
break
|
||||
```
|
||||
|
||||
## 数据类型相关
|
||||
|
||||
### `bool()`
|
||||
|
||||
将给定参数转换为布尔类型,如果没有参数,返回 False
|
||||
|
||||
### `int()`
|
||||
|
||||
将一个字符串或数字转换为整型
|
||||
|
||||
### `float()`
|
||||
|
||||
将整数和字符串转换成浮点数。
|
||||
|
||||
### `complex()`
|
||||
|
||||
将创建复数(complex numbers)。复数是由实部和虚部组成的,通常写作 `a + bj` 的形式,其中 `a` 是实部,`b` 是虚部,`j` 是虚数单位。
|
||||
|
||||
```python
|
||||
print(int())
|
||||
print(int('12'))
|
||||
print(int(3.6))
|
||||
print(int('0100',base=2)) # 将2进制的 0100 转化成十进制。结果为 4
|
||||
z1 = complex(2, 3) # 实部为 2,虚部为 3
|
||||
print(z1) # 输出: (2+3j)
|
||||
|
||||
```
|
||||
|
||||
## 进制转换相关
|
||||
|
||||
### `bin()`
|
||||
|
||||
将十进制转换成二进制并返回。
|
||||
|
||||
### `ocb()`
|
||||
|
||||
将十进制转化成八进制字符串并返回。
|
||||
|
||||
### `hex()`
|
||||
|
||||
将十进制转化成十六进制字符串并返回。
|
||||
|
||||
**示例**
|
||||
|
||||
```python
|
||||
print(bin(10),type(bin(10)))
|
||||
print(oct(10),type(oct(10)))
|
||||
print(hex(10),type(hex(10)))
|
||||
```
|
||||
|
||||
## 数学运算相关
|
||||
|
||||
### `abs()`
|
||||
|
||||
返回数字的绝对值。
|
||||
|
||||
### `divmod()`
|
||||
|
||||
计算除数与被除数的结果,返回一个包含商和余数的元组 `(a // b, a % b)`。
|
||||
|
||||
### `round()`
|
||||
|
||||
保留浮点数的小数位数,默认保留整数。
|
||||
|
||||
### `pow()`
|
||||
|
||||
函数是计算 x 的 y 次方,如果 z 存在,则再对结果进行取模,其结果等效于 `(pow(x,y) % z)`
|
||||
|
||||
**示例**
|
||||
|
||||
```python
|
||||
print(abs(-5)) # 5
|
||||
|
||||
print(divmod(7,2)) # (3, 1)
|
||||
|
||||
print(round(7/3,2)) # 2.33
|
||||
print(round(7/3)) # 2
|
||||
print(round(3.32567,3)) # 3.326
|
||||
|
||||
print(pow(2,3)) # 8
|
||||
print(pow(2,3,3)) # 2
|
||||
```
|
||||
|
||||
### `sum()`
|
||||
|
||||
对可迭代对象进行求和计算(可设置初始值)。
|
||||
|
||||
### `min()`
|
||||
|
||||
返回可迭代对象的最小值(可加 key,key 为函数名,通过函数的规则,返回最小值)。
|
||||
|
||||
### `max()`
|
||||
|
||||
返回可迭代对象的最大值(可加 key,key 为函数名,通过函数的规则,返回最大值)。
|
||||
|
||||
|
||||
**示例**
|
||||
|
||||
```python
|
||||
print(sum([1,2,3]))
|
||||
print(sum([1,2,3],100))
|
||||
|
||||
print(min([1,2,3]))
|
||||
|
||||
ret = min([1,2,3,-10],key=abs)
|
||||
print(ret)
|
||||
|
||||
print(max([1,2,3]))
|
||||
|
||||
ret = max([1,2,3,-10],key=abs)
|
||||
print(ret)
|
||||
|
||||
```
|
||||
|
||||
## 数据结构相关
|
||||
|
||||
### `list()`
|
||||
|
||||
将一个可迭代对象转化成列表(如果是字典,默认将 key 作为列表的元素)。
|
||||
|
||||
### `tuple()`
|
||||
|
||||
将一个可迭代对象转化成元祖(如果是字典,默认将 key 作为元祖的元素)。
|
||||
|
||||
### `dict()`
|
||||
|
||||
创建一个字典。
|
||||
|
||||
### `set()`
|
||||
|
||||
创建一个集合。
|
||||
|
||||
### `frozenset()`
|
||||
|
||||
创建一个冻结的集合。
|
||||
|
||||
|
||||
```python
|
||||
l = list((1,2,3))
|
||||
print(l)
|
||||
l = list({1,2,3})
|
||||
print(l)
|
||||
l = list({'k1':1,'k2':2})
|
||||
print(l)
|
||||
|
||||
tu = tuple((1,2,3))
|
||||
print(tu)
|
||||
tu = tuple([1,2,3])
|
||||
print(tu)
|
||||
tu = tuple({'k1':1,'k2':2})
|
||||
print(tu)
|
||||
```
|
||||
|
||||
## 字符串相关
|
||||
|
||||
### `str()`
|
||||
|
||||
将数据转化成字符串。
|
||||
|
||||
### `format()`
|
||||
|
||||
具体数据相关,用于计算各种小数,精算等。
|
||||
|
||||
```python
|
||||
# 字符串可以提供的参数,指定对齐方式,<是左对齐, >是右对齐,^是居中对齐
|
||||
print(format('test','<20'))
|
||||
print(format('test','>20'))
|
||||
print(format('test','^20'))
|
||||
|
||||
# 整形数值可以提供的参数有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
|
||||
print(format(192,'b')) # 转换为二进制
|
||||
print(format(97,'c')) # 转换unicode成字符
|
||||
print(format(11,'d')) # 转换成10进制
|
||||
print(format(11,'o')) # 转换为8进制
|
||||
print(format(11,'x')) # 转换为16进制,小写字母表示
|
||||
print(format(11,'X')) # 转换为16进制,大写字母表示
|
||||
print(format(11,'n')) # 和d一样
|
||||
print(format(11)) # 和d一样
|
||||
|
||||
# 浮点数可以提供的参数有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None
|
||||
print(format(314159265,'e')) # 科学计数法,默认保留6位小数
|
||||
print(format(314159265,'0.2e')) # 科学计数法,保留2位小数
|
||||
print(format(314159265,'0.2E')) # 科学计数法,保留2位小数,大写E
|
||||
print(format(3.14159265,'f')) # 小数点计数法,默认保留6位小数
|
||||
print(format(3.14159265,'0.10f')) # 小数点计数法,保留10位小数
|
||||
print(format(3.14e+10000,'F')) # 小数点计数法,无穷大转换成大小字母
|
||||
|
||||
# g的格式化比较特殊,假设p为格式中指定的保留小数位数,先尝试采用科学计数法格式化,得到幂指数exp,如果-4<=exp<p,则采用小数计数法,并保留p-1-exp位小数,否则按小数计数法计数,并按p-1保留小数位数
|
||||
print(format(0.00003141566,'.1g'))
|
||||
# p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点
|
||||
print(format(0.00003141566,'.2g'))
|
||||
# p=2,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点
|
||||
|
||||
print(format(3.1415926777,'.1g'))
|
||||
# p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留0位小数点
|
||||
print(format(3.1415926777,'.2g'))
|
||||
# p=2,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留1位小数点
|
||||
print(format(3141.5926777,'.2g'))
|
||||
# p=2,exp=3 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点
|
||||
|
||||
print(format(0.00003141566,'.1n')) # 和g相同
|
||||
print(format(0.00003141566)) # 和g相同
|
||||
```
|
||||
|
||||
### `repr()`
|
||||
|
||||
返回一个对象的 string 形式
|
||||
|
||||
```python
|
||||
name = 'EaglesLab'
|
||||
print('Hello %r' % name)
|
||||
|
||||
str1 = '{"name":"EaglesLab"}'
|
||||
print(repr(str1))
|
||||
print(str1)
|
||||
```
|
||||
|
||||
## 数据结构操作相关
|
||||
|
||||
### `reversed()`
|
||||
|
||||
将一个序列翻转,并返回此翻转序列的迭代器。
|
||||
|
||||
### `slice()`
|
||||
|
||||
构造一个切片对象,用于列表的切片。
|
||||
|
||||
```python
|
||||
ite = reversed(['a',2,4,'f',12,6])
|
||||
for i in ite:
|
||||
print(i)
|
||||
|
||||
l = ['a','b','c','d','e','f','g']
|
||||
sli = slice(3)
|
||||
print(l[sli])
|
||||
|
||||
sli = slice(0,7,2) # 也可以加上步长
|
||||
print(l[sli])
|
||||
```
|
||||
|
||||
### `len()`
|
||||
|
||||
返回一个对象中元素的个数。
|
||||
|
||||
### `sorted()`
|
||||
|
||||
对所有可迭代的对象进行排序操作。
|
||||
|
||||
```python
|
||||
numbers = [5, 2, 9, 1, 5, 6] # 升序
|
||||
sorted_numbers = sorted(numbers)
|
||||
print(sorted_numbers) # 输出: [1, 2, 5, 5, 6, 9]
|
||||
|
||||
numbers = [5, 2, 9, 1, 5, 6] # 降序
|
||||
sorted_numbers_desc = sorted(numbers, reverse=True)
|
||||
print(sorted_numbers_desc) # 输出: [9, 6, 5, 5, 2, 1]
|
||||
|
||||
# 可以使用 key 参数指定一个函数,用于从元素中提取用于排序的比较键
|
||||
words = ['banana', 'apple', 'cherry']
|
||||
sorted_words = sorted(words, key=len)
|
||||
print(sorted_words) # 输出: ['apple', 'banana', 'cherry']
|
||||
```
|
||||
|
||||
### `enumerate()`
|
||||
|
||||
将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
|
||||
|
||||
```python
|
||||
print(enumerate([1,2,3]))
|
||||
|
||||
for i in enumerate([1,2,3]):
|
||||
print(i)
|
||||
|
||||
for i in enumerate([1,2,3],100):
|
||||
print(i)
|
||||
```
|
||||
|
||||
### `all()`
|
||||
|
||||
可迭代对象中,全都是True才是True。
|
||||
|
||||
### `any()`
|
||||
|
||||
可迭代对象中,有一个True 就是True
|
||||
|
||||
```python
|
||||
print(all([1,2,True,0]))
|
||||
print(any([1,'',0]))
|
||||
```
|
||||
|
||||
### `zip()`
|
||||
|
||||
将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同。
|
||||
|
||||
```python
|
||||
names = ['zhangsan', 'lisi', 'wangwu']
|
||||
ages = [25, 30, 35, 40]
|
||||
|
||||
zipped = zip(names, ages)
|
||||
print(list(zipped))
|
||||
```
|
||||
|
||||
### `filter()`
|
||||
|
||||
过滤序列中不符合条件的元素,返回由符合元素组成的新的迭代器。
|
||||
|
||||
```python
|
||||
def func(x):
|
||||
return x % 2 == 0
|
||||
ret = filter(func,[1,2,3,4,5,6,7,8,9,10])
|
||||
print(ret)
|
||||
for i in ret:
|
||||
print(i)
|
||||
|
||||
# 过滤出大于 5 的数字
|
||||
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
filtered_numbers = filter(lambda x: x > 5, numbers)
|
||||
print(list(filtered_numbers)) # 输出: [6, 7, 8, 9]
|
||||
```
|
||||
|
||||
### `map()`
|
||||
将指定函数应用于可迭代对象中的每个元素,并返回一个迭代器。这个函数非常有用,可以简化对数据的转换和处理。
|
||||
|
||||
```python
|
||||
def square(x):
|
||||
return x**2
|
||||
|
||||
list1 = [1,2,3,4,5,6,7,8]
|
||||
|
||||
ret = map(square,list1)
|
||||
print(ret)
|
||||
|
||||
for i in ret:
|
||||
print(i)
|
||||
```
|
||||
|
||||
# 匿名函数
|
||||
|
||||
在 Python 中,匿名函数是指没有名称的函数,通常使用 `lambda` 关键字定义。匿名函数可以用于需要函数作为参数的场合,比如在 `map()`、`filter()` 和 `sorted()` 等函数中。
|
||||
|
||||
也可以理解为,为了解决那些功能很简单的需求而设计的一句话函数。
|
||||
|
||||
## 语法
|
||||
|
||||
```python
|
||||
lambda 参数: 表达式
|
||||
```
|
||||
|
||||
- 参数可以有多个,用逗号隔开
|
||||
- 匿名函数不管逻辑多复杂,只能写一行,且逻辑执行结束后的内容就是返回值
|
||||
- 返回值和正常的函数一样可以是任意数据类型
|
||||
|
||||
示例:
|
||||
|
||||
```python
|
||||
# 自定义函数的方法
|
||||
def func1(n):
|
||||
return n ** n
|
||||
|
||||
print(func1(10))
|
||||
|
||||
# 换成匿名函数
|
||||
func2 = lambda n: n ** n
|
||||
print(func2(10))
|
||||
```
|
||||
|
||||
## 案例
|
||||
|
||||
1. 计算两个数的和
|
||||
|
||||
```python
|
||||
add = lambda x, y: x + y
|
||||
print(add(2, 3)) # 输出: 5
|
||||
```
|
||||
|
||||
2. 配合 `map()` 使用
|
||||
|
||||
```python
|
||||
list1 = [1,2,3,4,5,6,7,8]
|
||||
|
||||
ret = map(lambda x: x ** 2,list1)
|
||||
print(ret)
|
||||
|
||||
for i in ret:
|
||||
print(i)
|
||||
```
|
||||
|
||||
3. 配合 `filter()` 使用
|
||||
|
||||
```python
|
||||
ret = filter(lambda x: x % 2 == 0,[1,2,3,4,5,6,7,8,9,10])
|
||||
print(ret)
|
||||
for i in ret:
|
||||
print(i)
|
||||
```
|
Reference in New Issue
Block a user