语法

"""
    函数式编程 -- 语法
"""
def fun01():
    print("fun01执行喽")

# 1. 函数可以赋值给变量
a = fun01
# 通过变量调用函数
a()# 活的
fun01()# 死的

# 2. 将函数作为参数传递
# 如果传入基本数据类型(整数/小数/字符串..),称之为传入数据
# 如果传入函数,称之为传入行为/逻辑/算法
def fun02(func):
    print("fun02执行喽")
    func()

fun02(fun01)

 思想

"""
    函数式编程 -- 思想
"""

list01 = [4,5,5,6,767,8,10]

"""
# 1. 找出所有偶数
def find01():
    for item in list01:
        if item % 2 == 0:
            yield item
            
# 2. 找出所有奇数
def find02():
    for item in list01:
        if item % 2:
            yield item

# 3. 找出所有大于10
def find03():
    for item in list01:
        if item  > 10:
            yield item
"""
# "封装":提取变化
def condition01(item):
    return item % 2 == 0

def condition02(item):
    return item % 2

def condition03(item):
    return item  > 10

# "继承":隔离变化
# 根据任何条件,在任何可迭代对象中查找多个元素.
def find(target,func):
    for item in target:
        # if item > 10:
        # if condition03(item):
        if func(item):
            yield item

# "多态":执行变化
for item in find(list01,condition03):
    print(item)

 

 函数作为参数

from common.list_helper import ListHelper

class Skill:
    def __init__(self, id=0,name="", atk=0, duration=0.1):
        self.id = id
        self.name = name
        self.atk = atk
        self.duration = duration

list01 = [
    Skill(101,"葵花宝典",850,10),
    Skill(102,"辟邪剑法",800,5),
    Skill(103,"狮吼功",500,8),
    Skill(104,"降龙十八掌",700,3),
    Skill(105,"电炮飞脚",8,2)
]

def condition01(item):
    return item.atk > 10

def condition02(item):
    return  2 <= item.duration <= 10

def condition03(item):
    return len(item.name) > 3

for item in ListHelper.find_all(list01, condition02):
    print(item.name)
"""
     工具类:定义针对可迭代对象的常用操作
"""

class ListHelper:
    """
        列表助手类
    """
    @staticmethod
    def find_all(iterable, func_condition):
        """
            根据指定条件,在可迭代对象中查找多个元素.
        :param target:
        :param func_condition: 函数类型的查找条件
              func_condition(可迭代对象中的元素) --> bool
        :return:所有满足的条件
        """
        for item in iterable:
            if func_condition(item):
                yield item

 

 匿名函数(lambda)

# 定义有参数lambda
func = lambda item:item % 2 == 0
re = func(5)
print(re)

# 定义无参数lambda
func = lambda :100
re = func()
print(re)

# 定义多个参数lambda
func =lambda a,b,c:a+b+c
re = func(1,2,3)
print(re)

# 定义无返回值lambda
func = lambda a:print("变量是:",a)
func(10)
# lambda 不支持赋值语句
# func = lambda obj:obj.a = 100

# lambda 只支持一条语句
# lambda a,b:if a % 2 == 0: print(a+b)
list01 = [4,5,5,6,767,8,10]

# def condition01(item):
#     return item % 2 == 0
#
# def condition02(item):
#     return item % 2
#
# def condition03(item):
#     return item  > 10

def find(target,func):
    for item in target:
        if func(item):
            yield item

# for item in find(list01,condition03):
#     print(item)

for item in find(list01,lambda item:item  > 10):
    print(item)

 

 ---------------------------------------------------------------------------------------

 

"""
    练习1:
    需求:
    定义函数, 在技能列表中, 计算技能名称大于3个字的技能数量
    定义函数, 在技能列表中, 计算攻击力大于500的技能数量
    定义函数, 在技能列表中, 查找持续时间在5--10之间的技能数量
    目标: 在ListHelper中定义计算满足指定条件的元素数量
    要求:使用lambda调用ListHelper
"""

print(ListHelper.get_count(list01,lambda item:len(item.name) > 3))
print(ListHelper.get_count(list01,lambda item:item.atk > 500))
print(ListHelper.get_count(list01,lambda item:5 <= item.duration<=10))


"""
    练习2:
    需求:
    定义函数, 在技能列表中, 判断是否存在编号是105的技能
    定义函数, 在技能列表中, 判断是否存在"九阳神功"技能
    定义函数, 在技能列表中, 判断是否攻击力大于10的技能
    目标: 在ListHelper中定义判断是否具有满足条件的元素
    要求:使用lambda调用ListHelper
"""

print(ListHelper.is_exists(list01,lambda element:element.id == 105))
print(ListHelper.is_exists(list01,lambda element:element.name == "九阳神功"))
print(ListHelper.is_exists(list01,lambda element:element.atk> 10))

"""
    练习3:
    需求:
    定义函数, 在技能列表中, 计算所有攻击力的和
    定义函数, 在技能列表中, 计算所有持续时间的和 
    目标: 在ListHelper中定义根据条件求和的方法
"""

print(ListHelper.sum(list01,lambda e:e.atk))
print(ListHelper.sum(list01,lambda e:e.duration))


"""
    练习4:
    需求:
    定义函数, 在技能列表中, 获取所有技能的名称与攻击力.
    定义函数, 在技能列表中, 获取所有技能的编号与名称与持续时间.
    目标: 在ListHelper中定义根据条件筛选信息的函数
"""

for item in ListHelper.select(list01,lambda info:(info.id,info.atk)):
    print(item)

for item in ListHelper.select(list01,lambda info:(info.id,info.name,info.duration)):
    print(item)

"""
    练习5:
    需求:
    定义函数, 在技能列表中, 获取攻击力最大的技能.
    定义函数, 在技能列表中, 获取持续时间最大的技能.
    目标: 在ListHelper中定义根据指定条件获取最大元素的功能
"""

max = ListHelper.get_max(list01,lambda item:item.atk)
print(max.name)
max = ListHelper.get_max(list01,lambda item:item.duration)
print(max.name)

 

"""
     工具类:定义针对可迭代对象的常用操作
     微软 LINQ  语言集成查询框架
     集成操作框架
"""

class ListHelper:
    """
        列表助手类
    """

    @staticmethod
    def get_count(iterable, func_condition):
        """
             在可迭代对象中获取满足条件的元素数量.
         :param iterable:需要检索的可迭代对象
         :param func_condition: 函数类型的查找条件
               func_condition(可迭代对象中的元素) --> bool
         :return:满足条件的数量
         """
        count = 0
        for item in iterable:
            if func_condition(item):
                count += 1
        return count

    @staticmethod
    def is_exists(iterable, func_condition):
        """
             在可迭代对象中判断是否具有满足条件的元素.
         :param iterable:需要检索的可迭代对象
         :param func_condition: 函数类型的查找条件
               func_condition(可迭代对象中的元素) --> bool
         :return:是否存在 True表示存在,False表示不存在
         """
        for item in iterable:
            if func_condition(item):
                return True
        return False

    @staticmethod
    def sum(iterable, func_condition):
        """
             在可迭代对象中根据指定条件进行求和计算
         :param iterable:需要求和的可迭代对象
         :param func_condition: 函数类型的求和条件
               func_condition(可迭代对象中的元素) --> 任意类型
         :return:求和的结果
         """
        sum_value = 0
        for item in iterable:
            sum_value += func_condition(item)
        return sum_value

    @staticmethod
    def select(iterable, func_condition):
        """
             在可迭代对象中根据指定条件对每个元素进行筛选
         :param iterable:需要筛选的可迭代对象
         :param func_condition: 函数类型的筛选条件
               func_condition(可迭代对象中的元素) --> 任意类型
         :return:生成器对象类型的筛选结果
         """
        for item in iterable:
            yield func_condition(item)

    @staticmethod
    def get_max(iterable, func_condition):
        """
             在可迭代对象中根据指定条件获取最大元素
         :param iterable:需要搜索的可迭代对象
         :param func_condition: 函数类型的搜索条件
               func_condition(可迭代对象中的元素) --> 任意类型
         :return:最大元素
         """
        max_item = iterable[0]
        for i in range(1, len(iterable)):
            # if max_item.atk <  iterable[i].atk:
            # if max_item.duration <  iterable[i].duration:
            if func_condition(max_item) < func_condition(iterable[i]):
                max_item = iterable[i]
        return max_item

    @staticmethod
    def order_by(iterable, func_condition):
        """
             根据指定条件对可迭代对象进行升序排列
         :param iterable:需要排序的可迭代对象
         :param func_condition: 函数类型的排序依据
               func_condition(可迭代对象中的元素) --> 任意类型
         """
        for r in range(len(iterable) - 1):
            for c in range(r + 1, len(iterable)):
                # if iterable[r].atk > iterable[c].atk:
                if func_condition(iterable[r]) > func_condition(iterable[c]):
                    iterable[r], iterable[c] = iterable[c], iterable[r]

    # 获取最小
    # 降序
    # 删除

 

内置高阶函数

class Wife:
    def __init__(self, name, age, weight, height):
        self.name = name
        self.age = age
        self.weight = weight
        self.height = height

list01 = [
    Wife("翠花", 36, 60, 1.5),
    Wife("如花", 39, 75, 1.3),
    Wife("赵敏", 25, 46, 1.7),
    Wife("灭绝", 42, 50, 1.8)
]

# 1. 过滤:根据条件筛选可迭代对象中的元素,返回值为新可迭代对象。
for item in filter(lambda item:item.age < 40,list01):
    print(item.name)

# 2. 映射:使用可迭代对象中的每个元素调用函数,将返回值作为新可迭代对象元素;
for item in map(lambda item:(item.name,item.age),list01):
    print(item)

# 3. 升序排列
for item in sorted(list01,key = lambda item:item.height):
    print(item.height)

# 4. 降序排列
for item in sorted(list01,key = lambda item:item.height,reverse=True):
    print(item.height)

# 5. 获取最大值
re = max(list01, key=lambda item: item.weight)
print(re.name)

# 6. 获取最小值
re = min(list01, key=lambda item: item.weight)
print(re.name)
posted on 2019-07-22 01:21  _never  阅读(137)  评论(0编辑  收藏  举报