Python——函数式编程

函数式编程:
    主体相同,核心算法不同,想到用函数编程
    【本质】:隔离通用代码和变化点, 提高代码复用率

语法:
    def func01():
        通用代码
        condition1  # 变化点1
    
    def func02():
        通用代码
        condition2  # 变化点2
        
推导>
    def func(变化点):
        通用代码
        变化点

调用:func(lambda 参数: 函数体)
        【注】:其中lambda函数就是condition的具体函数代码,只不过是将def定义的形式改成了lambda形式

代码目录结构

通用代码定义文件

iterable_tools.py

class IterableHelper:
    """
        可迭代对象助手类:对可迭代对象常用的高阶函数
    """

    # 静态方法:不操作实例成员/类成员
    @staticmethod
    def find_single(iterable, condition):
        """
            在可迭代对象中,查找满足条件的第一个元素
        :param iterable: 可迭代对象
        :param condition: 函数类型的查找条件
        :return: 满足条件的第一个元素
        """
        for item in iterable:
            if condition(item):
                return item

    @staticmethod
    def find_all(iterable, condition):
        """
            在可迭代对象中,查找满足条件的所有元素
        :param iterable: 可迭代对象
        :param condition: 函数类型的查找条件
        :return: 生成器,推算满足条件的元素
        """
        for item in iterable:
            if condition(item):
                yield item

    @staticmethod
    def sum(iterable, condition):
        """
            在可迭代对象中,查找条件累加
        :param iterable: 可迭代对象
        :param condition: 函数类型的累加条件
        :return: 数值类型,累加和
        """
        sum_value = 0
        for item in iterable:
            sum_value += condition(item)
        return sum_value

    @staticmethod
    def delete_all(iterable, condition):
        """

        :param iterable:
        :param condition:
        :return:
        """
        count = 0
        for i in range(len(iterable) - 1, -1, -1):
            if condition(iterable[i]):
                del iterable[i]
                count += 1
        return count

    @staticmethod
    def select(iterable, condition):
        """
            在可迭代对象中根据条件选择成员
        :param iterable: 可迭代对象
        :param condition: 函数类型的选择策略
        :return: 生成器,推算出元素的成员
        """
        for item in iterable:
            yield condition(item)

    @staticmethod
    def get_count(iterable, condition):
        """
            在可迭代对象中计算满足条件的元素数量
        :param iterable: 可迭代对象
        :param condition: 函数类型的条件
        :return: int类型,数量
        """
        count = 0
        for item in iterable:
            if condition(item):
                count += 1
        return count

    @staticmethod
    def get_max(iterable, condition):
        """
            在可迭代对象中,根据条件查找
        :param iterable: 可迭代对象
        :param condition: 函数类型,查找策略
        :return: 最大值
        """
        max_value = iterable[0]
        for i in range(1, len(iterable)):
            if condition(max_value) < condition(iterable[i]):
                max_value = iterable[i]
        return max_value

    @staticmethod
    def is_repeat(iterable, condition):
        """
            在可迭代对象中根据条件判断是否有重复的元素
        :param iterable: 可迭代对象
        :param condition: 函数类型,判断条件
        :return: bool类型,True表示有重复,Flase表示没有重复
        """
        for r in range(len(iterable) - 1):
            for c in range(r + 1, len(iterable)):
                if condition(iterable[r]) == condition(iterable[c]):
                    return True
        return False

    @staticmethod
    def order_by(iterable, condition):
        """
            根据条件对可迭代对象升序排列
        :param iterable: 可迭代对象
        :param condition: 函数类型,排序依据
        """
        for r in range(len(iterable) - 1):
            for c in range(r + 1, len(iterable)):
                if condition(iterable[r]) > condition(iterable[c]):
                    iterable[r], iterable[c] = iterable[c], iterable[r]

调用文件

demo01.py

from common.iterable_tools import IterableHelper

class Employee:
    def __init__(self, eid, did, name, money):
        self.eid = eid  # 员工编号
        self.did = did  # 部门编号
        self.name = name  # 员工编号
        self.money = money  # 员工薪资


list_employees = [
    Employee(1001, 9002, "师父", 60000),
    Employee(1002, 9001, "孙悟空", 50000),
    Employee(1003, 9002, "猪八戒", 20000),
    Employee(1004, 9001, "沙僧", 30000),
    Employee(1005, 9001, "小白龙", 15000),
    Employee(1006, 9003, "小白龙", 9000)
]

# 按照员工薪资升序排序员工的信息
print("Q0:按照员工薪资升序排序员工的信息")
IterableHelper.order_by(list_employees, lambda emp: emp.money)
for emp in list_employees:
    print(emp.__dict__)
print()

# 判断是否有重复
print("Q1:判断是否有名字重复的员工")
print(IterableHelper.is_repeat(list_employees, lambda e: e.name))
print()

# 查找满足条件的所有元素
print("Q2:查找员工编号为9001的所有员工")
for emp in IterableHelper.find_all(list_employees, lambda item: item.did == 9001):
    print(emp.__dict__)
print()

# 查找满足条件的首个元素
print("Q3:查找姓名长度为2的首个元素")
emp = IterableHelper.find_single(list_employees, lambda item: len(item.name) == 2)
print(emp.__dict__)
print()

# 计算满足条件的所有元素个数并返回
print("Q4:计算员工部门id为9001的员工个数并返回")
result = IterableHelper.get_count(list_employees, lambda item: item.did == 9001)
print(result)
print()

# 删除满足条件的所有元素
print("Q5:删除名字为孙悟空的员工")
IterableHelper.delete_all(list_employees, lambda item: item.name == "孙悟空")
for emp in list_employees:
    print(emp.__dict__)
print()

# 输出所有元素的某个属性
print("Q6:输出姓名长度为3的所有员工信息")
for name in IterableHelper.select(list_employees, lambda item: item.name):
    print(name)
print()

# 获取满足条件的元素的数量
print("Q7:获取薪资大于20000的员工数量")
result = IterableHelper.sum(list_employees, lambda item: item.money > 20000)
print(result)

 输出结果

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值