简单的python-核心篇-函数式编程_好玩又简单的python函数代码
itomcoil 2025-10-23 03:53 1 浏览
函数是Python的一等公民,可以作为参数传递、作为返回值返回、赋值给变量或存储在数据结构中。
# 函数可以赋值给变量
def greet(name):
return f"Hello, {name}!"
say_hello = greet
print(say_hello("Alice")) # Hello, Alice!
# 函数可以作为参数
def apply_operation(func, value):
return func(value)
def square(x):
return x ** 2
result = apply_operation(square, 5)
print(result) # 25
# 函数可以作为返回值
def create_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
double = create_multiplier(2)
triple = create_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
高阶函数
高阶函数(Higher-order functions)是接受函数作为参数或返回函数的函数。
1. map函数
# 传统方式
numbers = [1, 2, 3, 4, 5]
squared = []
for num in numbers:
squared.append(num ** 2)
# 函数式方式
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# 使用自定义函数
def square(x):
return x ** 2
squared = list(map(square, numbers))
print(squared) # [1, 4, 9, 16, 25]
# 多个序列
names = ["alice", "bob", "charlie"]
ages = [25, 30, 35]
info = list(map(lambda name, age: f"{name} is {age}", names, ages))
print(info) # ['alice is 25', 'bob is 30', 'charlie is 35']
2. filter函数
# 过滤偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # [2, 4, 6, 8, 10]
# 过滤非空字符串
words = ["hello", "", "world", "", "python"]
non_empty = list(filter(None, words)) # None作为谓词函数
print(non_empty) # ['hello', 'world', 'python']
# 使用自定义函数
def is_long_word(word):
return len(word) > 4
long_words = list(filter(is_long_word, words))
print(long_words) # ['hello', 'world', 'python']
3. reduce函数
from functools import reduce
# 计算列表元素的和
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total) # 15
# 计算列表元素的最大值
max_value = reduce(lambda x, y: x if x > y else y, numbers)
print(max_value) # 5
# 字符串连接
words = ["Hello", "World", "Python"]
sentence = reduce(lambda x, y: f"{x} {y}", words)
print(sentence) # Hello World Python
# 使用初始值
total_with_init = reduce(lambda x, y: x + y, numbers, 10)
print(total_with_init) # 25 (10 + 1 + 2 + 3 + 4 + 5)
Lambda表达式
Lambda表达式是创建匿名函数的简洁方式。
# 基本语法
square = lambda x: x ** 2
print(square(5)) # 25
# 多个参数
add = lambda x, y: x + y
print(add(3, 4)) # 7
# 在函数中使用
def apply_operation(numbers, operation):
return [operation(x) for x in numbers]
numbers = [1, 2, 3, 4, 5]
squared = apply_operation(numbers, lambda x: x ** 2)
cubed = apply_operation(numbers, lambda x: x ** 3)
print(squared) # [1, 4, 9, 16, 25]
print(cubed) # [1, 8, 27, 64, 125]
# 条件表达式
abs_value = lambda x: x if x >= 0 else -x
print(abs_value(-5)) # 5
print(abs_value(5)) # 5
列表推导式与生成器表达式
1. 列表推导式
# 基本语法
squares = [x ** 2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
# 嵌套循环
matrix = [[i * j for j in range(3)] for i in range(3)]
print(matrix) # [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
# 复杂表达式
words = ["hello", "world", "python"]
word_info = [(word, len(word), word.upper()) for word in words]
print(word_info) # [('hello', 5, 'HELLO'), ('world', 5, 'WORLD'), ('python', 6, 'PYTHON')]
2. 生成器表达式
# 生成器表达式(使用圆括号)
squares_gen = (x ** 2 for x in range(10))
print(type(squares_gen)) # <class 'generator'>
# 惰性求值
for square in squares_gen:
if square > 20:
break
print(square) # 0, 1, 4, 9, 16
# 内存效率
import sys
# 列表推导式
list_comp = [x ** 2 for x in range(1000)]
print(f"列表推导式大小: {sys.getsizeof(list_comp)}")
# 生成器表达式
gen_expr = (x ** 2 for x in range(1000))
print(f"生成器表达式大小: {sys.getsizeof(gen_expr)}")
闭包与装饰器
1. 闭包
def create_counter(initial=0):
"""创建计数器函数"""
count = initial
def counter():
nonlocal count
count += 1
return count
return counter
# 创建不同的计数器
counter1 = create_counter(0)
counter2 = create_counter(10)
print(counter1()) # 1
print(counter1()) # 2
print(counter2()) # 11
print(counter2()) # 12
# 闭包保持状态
def create_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
double = create_multiplier(2)
triple = create_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
# 检查闭包
print(double.__closure__[0].cell_contents) # 2
2. 装饰器
import functools
import time
# 基本装饰器
def timer(func):
"""计时装饰器"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} 执行时间: {end - start:.4f}秒")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "完成"
result = slow_function()
# 带参数的装饰器
def repeat(times):
"""重复执行装饰器"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
# 类装饰器
class CountCalls:
def __init__(self, func):
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
print(f"{self.func.__name__} 被调用了 {self.count} 次")
return self.func(*args, **kwargs)
@CountCalls
def say_hello():
print("Hello!")
say_hello() # Hello! say_hello 被调用了 1 次
say_hello() # Hello! say_hello 被调用了 2 次
函数式编程工具
1. functools模块
from functools import partial, reduce, wraps
# partial - 部分应用
def multiply(x, y):
return x * y
double = partial(multiply, 2)
triple = partial(multiply, 3)
print(double(5)) # 10
print(triple(5)) # 15
# 更复杂的例子
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(5)) # 25
print(cube(5)) # 125
# reduce - 累积操作
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) # 120
# 自定义reduce函数
def my_reduce(func, iterable, initial=None):
iterator = iter(iterable)
if initial is None:
try:
initial = next(iterator)
except StopIteration:
raise TypeError("reduce() of empty sequence with no initial value")
for element in iterator:
initial = func(initial, element)
return initial
result = my_reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
print(result) # 15
2. itertools模块
import itertools
# 无限迭代器
counter = itertools.count(1, 2) # 从1开始,步长为2
print(list(itertools.islice(counter, 5))) # [1, 3, 5, 7, 9]
# 循环迭代器
cycle = itertools.cycle(['A', 'B', 'C'])
print(list(itertools.islice(cycle, 7))) # ['A', 'B', 'C', 'A', 'B', 'C', 'A']
# 重复迭代器
repeat = itertools.repeat('Hello', 3)
print(list(repeat)) # ['Hello', 'Hello', 'Hello']
# 组合和排列
letters = ['A', 'B', 'C']
combinations = list(itertools.combinations(letters, 2))
permutations = list(itertools.permutations(letters, 2))
print(combinations) # [('A', 'B'), ('A', 'C'), ('B', 'C')]
print(permutations) # [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
# 分组
data = [1, 1, 2, 2, 2, 3, 3, 3, 3]
grouped = itertools.groupby(data)
for key, group in grouped:
print(f"{key}: {list(group)}")
# 输出:
# 1: [1, 1]
# 2: [2, 2, 2]
# 3: [3, 3, 3, 3]
函数式编程模式
1. 管道模式
def pipe(*functions):
"""创建函数管道"""
def pipeline(value):
for func in functions:
value = func(value)
return value
return pipeline
# 使用管道
def add_one(x):
return x + 1
def multiply_by_two(x):
return x * 2
def square(x):
return x ** 2
# 创建管道:加1 -> 乘2 -> 平方
pipeline = pipe(add_one, multiply_by_two, square)
result = pipeline(3) # ((3 + 1) * 2) ** 2 = 64
print(result)
# 更复杂的管道
def filter_even(numbers):
return [x for x in numbers if x % 2 == 0]
def square_numbers(numbers):
return [x ** 2 for x in numbers]
def sum_numbers(numbers):
return sum(numbers)
data_pipeline = pipe(filter_even, square_numbers, sum_numbers)
result = data_pipeline([1, 2, 3, 4, 5, 6]) # 2^2 + 4^2 + 6^2 = 56
print(result)
2. 柯里化
def curry(func):
"""柯里化装饰器"""
@functools.wraps(func)
def curried(*args, **kwargs):
if len(args) + len(kwargs) >= func.__code__.co_argcount:
return func(*args, **kwargs)
return lambda *args2, **kwargs2: curried(*(args + args2), **{**kwargs, **kwargs2})
return curried
@curry
def add_three_numbers(a, b, c):
return a + b + c
# 部分应用
add_5_and_10 = add_three_numbers(5, 10)
result = add_5_and_10(15) # 30
print(result)
# 链式调用
result = add_three_numbers(5)(10)(15) # 30
print(result)
函数式编程的最佳实践
1. 纯函数
# 纯函数:相同输入总是产生相同输出,无副作用
def pure_add(a, b):
return a + b
# 非纯函数:有副作用
total = 0
def impure_add(a, b):
global total
total += a + b
return total
# 测试纯函数
print(pure_add(2, 3)) # 5
print(pure_add(2, 3)) # 5 (总是相同结果)
# 测试非纯函数
print(impure_add(2, 3)) # 5
print(impure_add(2, 3)) # 10 (结果不同)
2. 不可变性
# 使用不可变数据结构
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
# 创建点
p1 = Point(1, 2)
p2 = Point(3, 4)
# 不能修改,只能创建新的
# p1.x = 5 # AttributeError: can't set attribute
# 创建新点
p3 = Point(p1.x + p2.x, p1.y + p2.y)
print(p3) # Point(x=4, y=6)
# 使用frozenset
frozen_set = frozenset([1, 2, 3])
# frozen_set.add(4) # AttributeError: 'frozenset' object has no attribute 'add'
3. 函数组合
def compose(*functions):
"""函数组合"""
def composed(x):
for func in reversed(functions):
x = func(x)
return x
return composed
# 定义简单函数
def add_one(x):
return x + 1
def multiply_by_two(x):
return x * 2
def square(x):
return x ** 2
# 组合函数:先加1,再乘2,最后平方
composed_func = compose(square, multiply_by_two, add_one)
result = composed_func(3) # ((3 + 1) * 2) ** 2 = 64
print(result)
性能考虑
1. 生成器vs列表
import time
# 列表推导式
start = time.time()
squares_list = [x ** 2 for x in range(1000000)]
list_time = time.time() - start
# 生成器表达式
start = time.time()
squares_gen = (x ** 2 for x in range(1000000))
gen_time = time.time() - start
print(f"列表推导式时间: {list_time:.4f}秒")
print(f"生成器表达式时间: {gen_time:.4f}秒")
# 内存使用
import sys
print(f"列表大小: {sys.getsizeof(squares_list)}")
print(f"生成器大小: {sys.getsizeof(squares_gen)}")
2. 缓存优化
from functools import lru_cache
# 使用缓存优化递归函数
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
# 测试性能
import time
start = time.time()
result = fibonacci(35)
end = time.time()
print(f"fibonacci(35) = {result}")
print(f"执行时间: {end - start:.4f}秒")
写在最后
函数式编程不仅仅是编程范式,更是一种思维方式。它强调:
- 不可变性:避免状态变化带来的复杂性
- 纯函数:可预测、可测试、可并行
- 函数组合:通过简单函数的组合解决复杂问题
- 声明式:描述"做什么"而不是"怎么做"
Python虽然不是纯函数式语言,但它提供了丰富的函数式编程工具。掌握这些工具,我们能够:
- 写出更简洁、更可读的代码
- 提高代码的可测试性和可维护性
- 利用函数式编程的优势解决特定问题
- 在面向对象和函数式编程之间找到平衡
记住:函数式编程不是银弹,但它是一个强大的工具。在合适的场景下使用,能让我们的代码更加优雅和高效。
相关推荐
-
- Python编程实现求解高次方程_python求次幂
-
#头条创作挑战赛#编程求解一元多次方程,一般情况下对于高次方程我们只求出近似解,较少的情况可以得到精确解。这里给出两种经典的方法,一种是牛顿迭代法,它是求解方程根的有效方法,通过若干次迭代(重复执行部分代码,每次使变量的当前值被计算出的新值...
-
2025-10-23 03:58 itomcoil
- python常用得内置函数解析——sorted()函数
-
接下来我们详细解析Python中非常重要的内置函数sorted()1.函数定义sorted()函数用于对任何可迭代对象进行排序,并返回一个新的排序后的列表。语法:sorted(iterabl...
- Python入门学习教程:第 6 章 列表
-
6.1什么是列表?在Python中,列表(List)是一种用于存储多个元素的有序集合,它是最常用的数据结构之一。列表中的元素可以是不同的数据类型,如整数、字符串、浮点数,甚至可以是另一个列表。列...
- Python之函数进阶-函数加强(上)_python怎么用函数
-
一.递归函数递归是一种编程技术,其中函数调用自身以解决问题。递归函数需要有一个或多个终止条件,以防止无限递归。递归可以用于解决许多问题,例如排序、搜索、解析语法等。递归的优点是代码简洁、易于理解,并...
- Python内置函数range_python内置函数int的作用
-
range类型表示不可变的数字序列,通常用于在for循环中循环指定的次数。range(stop)range(start,stop[,step])range构造器的参数必须为整数(可以是内...
- python常用得内置函数解析——abs()函数
-
大家号这两天主要是几个常用得内置函数详解详细解析一下Python中非常常用的内置函数abs()。1.函数定义abs(x)是Python的一个内置函数,用于返回一个数的绝对值。参数:x...
- 如何在Python中获取数字的绝对值?
-
Python有两种获取数字绝对值的方法:内置abs()函数返回绝对值。math.fabs()函数还返回浮点绝对值。abs()函数获取绝对值内置abs()函数返回绝对值,要使用该函数,只需直接调用:a...
- 贪心算法变种及Python模板_贪心算法几个经典例子python
-
贪心算法是一种在每一步选择中都采取当前状态下最优的选择,从而希望导致结果是全局最优的算法策略。以下是贪心算法的主要变种、对应的模板和解决的问题特点。1.区间调度问题问题特点需要从一组区间中选择最大数...
- Python倒车请注意!负步长range的10个高能用法,让代码效率翻倍
-
你是否曾遇到过需要倒着处理数据的情况?面对时间序列、日志文件或者矩阵操作,传统的遍历方式往往捉襟见肘。今天我们就来揭秘Python中那个被低估的功能——range的负步长操作,让你的代码优雅反转!一、...
- Python中while循环详解_python怎么while循环
-
Python中的`while`循环是一种基于条件判断的重复执行结构,适用于不确定循环次数但明确终止条件的场景。以下是详细解析:---###一、基本语法```pythonwhile条件表达式:循环体...
- 简单的python-核心篇-面向对象编程
-
在Python中,类本身也是对象,这被称为"元类"。这种设计让Python的面向对象编程具有极大的灵活性。classMyClass:"""一个简单的...
- 简单的python-python3中的不变的元组
-
golang中没有内置的元组类型,但是多值返回的处理结果模拟了元组的味道。因此,在golang中"元组”只是一个将多个值(可能是同类型的,也可能是不同类型的)绑定在一起的一种便利方法,通常,也...
- python中必须掌握的20个核心函数——sorted()函数
-
sorted()是Python的内置函数,用于对可迭代对象进行排序,返回一个新的排序后的列表,不修改原始对象。一、sorted()的基本用法1.1方法签名sorted(iterable,*,ke...
- 12 个 Python 高级技巧,让你的代码瞬间清晰、高效
-
在日常的编程工作中,我们常常追求代码的精简、优雅和高效。你可能已经熟练掌握了列表推导式(listcomprehensions)、f-string和枚举(enumerate)等常用技巧,但有时仍会觉...
- Python的10个进阶技巧:写出更快、更省内存、更优雅的代码
-
在Python的世界里,我们总是在追求效率和可读性的完美平衡。你不需要一个数百行的新框架来让你的代码变得优雅而快速。事实上,真正能带来巨大提升的,往往是那些看似微小、却拥有高杠杆作用的技巧。这些技巧能...
- 一周热门
- 最近发表
- 标签列表
-
- ps图案在哪里 (33)
- super().__init__ (33)
- python 获取日期 (34)
- 0xa (36)
- super().__init__()详解 (33)
- python安装包在哪里找 (33)
- linux查看python版本信息 (35)
- python怎么改成中文 (35)
- php文件怎么在浏览器运行 (33)
- eval在python中的意思 (33)
- python安装opencv库 (35)
- python div (34)
- sticky css (33)
- python中random.randint()函数 (34)
- python去掉字符串中的指定字符 (33)
- python入门经典100题 (34)
- anaconda安装路径 (34)
- yield和return的区别 (33)
- 1到10的阶乘之和是多少 (35)
- python安装sklearn库 (33)
- dom和bom区别 (33)
- js 替换指定位置的字符 (33)
- python判断元素是否存在 (33)
- sorted key (33)
- shutil.copy() (33)