函数使用进阶
# 函数使用进阶
## 高阶函数
高阶函数:函数可以作为参数或返回值。Python 中函数是"一等函数",可以赋值给变量、作为参数、作为返回值。
### 函数作为参数
```python
def calc(init_value, op_func, *args):
"""通用累加器"""
result = init_value
for val in args:
if isinstance(val, (int, float)):
result = op_func(result, val)
return result
from operator import add, mul
print(calc(0, add, 1, 2, 3, 4, 5)) # 15
print(calc(1, mul, 1, 2, 3, 4, 5)) # 120
```
### 内置高阶函数
```python
# filter - 过滤
nums = [35, 12, 8, 99, 60, 52]
even_sq = [x**2 for x in nums if x % 2 == 0] # 列表生成式
# map - 映射
names = ['alice', 'bob', 'charlie']
print(list(map(str.upper, names))) # ['ALICE', 'BOB', 'CHARLIE']
# sorted - 排序(支持自定义key)
words = ['in', 'apple', 'zoo', 'waxberry']
print(sorted(words, key=len)) # 按长度排序
```
## Lambda 函数
Lambda(匿名函数):没有名字的单行函数,适合一次性使用。
```python
# 基本语法
lambda x: x ** 2 # 等价于 def f(x): return x**2
lambda x, y: x + y # 多参数
# 应用示例
nums = [35, 12, 8, 99, 60, 52]
even_sq = list(map(lambda x: x**2, filter(lambda x: x%2==0, nums)))
```
## 偏函数
偏函数:固定函数的部分参数,生成新函数。
```python
import functools
int2 = functools.partial(int, base=2) # 二进制转十进制
int8 = functools.partial(int, base=8) # 八进制转十进制
print(int2('1001')) # 9
print(int8('1001')) # 513
```
## 总结
- 高阶函数:函数作为参数或返回值,`filter`、`map`、`sorted` 是常见内置高阶函数
- Lambda 函数:单行匿名函数,适合一次性、简单的函数
- 偏函数:固定部分参数,简化调用