Python学习第十七天

""" 复习"""def func01(): print("第1部分") yield "结果1" print("第2部分") yield "结果2" print("第3部分")"""class Generate: def __next__(self): print("第n部分") return "结果n""""# 调用函数返回生成器(推算数据),惰性操作/延迟操作result = func01()
摘要由CSDN通过智能技术生成
"""
    复习
"""
def func01():
    print("第1部分")
    yield "结果1"

    print("第2部分")
    yield "结果2"

    print("第3部分")

"""
class Generate:
    def __next__(self):
        print("第n部分")
        return "结果n"
"""

# 调用函数返回生成器(推算数据),惰性操作/延迟操作
result = func01()
data = result.__next__()
print(data)

data = result.__next__()
print(data)


内置生成器
枚举函数enumerate
1. 语法:
for 变量 in enumerate(可迭代对象):
语句
for 索引, 元素in enumerate(可迭代对象):
语句
2. 作用:遍历可迭代对象时,可以将索引与元素组合为一个元组。

"""
    内置生成器
"""
list01 = [54, 5, 6, 76, 8, 9]
# 遍历元素 -- 读取
for item in list01:
    print(item)

# 遍历索引 -- 修改
# for i in range(len(list01)):
#     list01[i] = 0

# 需求:修改奇数为0
# for i in range(len(list01)):
#     if list01[i] % 2:
#         list01[i] = 0

# (索引, 元素)
# for item in enumerate(list01):
for i, element in enumerate(list01):
    if element % 2:
        list01[i] = 0

print(list01)

zip
1. 语法:
for item in zip(可迭代对象1, 可迭代对象2….):
语句
2. 作用:将多个可迭代对象中对应的元素组合成一个个元组,生成的元组个数由最小的可迭代对象决定。

"""
    内置生成器
"""
list01 = ["a", "b", "c"]
list02 = ["A", "B", "C"]
for item in zip(list01, list02):
    print(item)

生成器表达式
1. 定义:用推导式形式创建生成器对象。
2. 语法:变量 = ( 表达式 for 变量 in 可迭代对象 [if 真值表达式] )

"""
    生成器函数
        给其他人用
    生成器表达式
        给自己使用

"""
list01 = [54, 65.5, True, "a", False, "b", 3, "c"]
# 查找所有字符串
# list_result = []
# for item in list01:
#     if type(item) == str:
#         list_result.append(item)
# print(list_result)

# 列表推导式
list_result = [item for item in list01 if type(item) == str]
for item in list_result:
    print(item)

# 生成器表达式
list_result = (item for item in list01
               if type(item) == str)
for item in list_result:
    print(item)

函数式编程
1. 定义:用一系列函数解决问题。
– 函数可以赋值给变量,赋值后变量绑定函数。
– 允许将函数作为参数传入另一个函数。
– 允许函数返回一个函数。
2. 高阶函数:将函数作为参数或返回值的函数

"""
    函数式编程 - 语法
        理论支柱:
            将函数赋值给变量,通过变量调用函数
        应用:
            将函数赋值给参数,通过参数调用函数
            (价值:通过参数调用函数,可以将(核心)逻辑注入到函数中.)
"""
def func01():
    print("func01执行了")

# 将函数赋值给变量
a = func01
# 通过变量调用函数
a()

def func02():
    print("func02执行了")

# 价值:通过参数调用函数,可以将(核心)逻辑注入到函数中.
def func03(a):
    print("func03执行了")
    a()# 执行?

func03(func01)
func03(func02)

lambda 表达式
1. 定义:是一种匿名方法。
2. 作用:作为参数传递时语法简洁,优雅,代码可读性强。
随时创建和销毁,减少程序耦合度。
3. 语法
– 定义:
变量 = lambda 形参: 方法体
– 调用:
变量(实参)
4. 说明:
– 形参没有可以不填
– 方法体只能有一条语句,且不支持赋值语句。

"""
    lambda 表达式
        匿名函数:
            lambda 参数: 函数体

            def不能转换为lambda写法
                1. lambda表达式不能赋值
                2. lambda 函数体只能有一条语句

            应用:作为实参
"""

# 写法1:有参数,有返回值
# def func01(p1, p2):
#     return p1 > p2
#
# print(func01(10, 5))

func01 = lambda p1, p2: p1 > p2
print(func01(10, 5))

# 写法2:有参数,无返回值
# def func02(p1):
#     print("参数是:",p1)
#
# func02(10)

func02 = lambda p1: print("参数是:", p1)
func02(10)

# 写法3:无参数,有返回值
# def func03():
#     return "结果"
#
# result = func03()
# print(result)

func03 = lambda: "结果"
result = func03()
print(result)

# 写法4:无参数,无返回值
# def func04():
#     print("func04执行喽")
#
# func04()

func04 = lambda: print("func04执行喽")
func04()

# def不能转换为lambda写法
def func05(p1):
    p1[0] = 100

list01 = [10]
func05(list01)
print(list01[0]) # 100

# 1. lambda表达式不能赋值
# func05 = lambda p1:p1[0] = 100


def func06():
    for i in range(5):
        print(i)

func06()

# 2. lambda 函数体只能有一条语句
# func06 = lambda :for i in range(5):
#                     print(i)



"""
    函数式编程 - 思想
        面向对象
            封装:分
            继承:隔
            多态:做
        函数式编程
            分:将通用和变化点分为多个函数
            隔:使用参数隔离具体变化的函数
            做:通常使用lambda定义变化函数
"""
list01 = [42, 45, 5, 66, 7, 89]


# 提取变化函数
# def condition01(item):
#     return item > 10
#
# def condition02(item):
#     return item % 2 == 0

# 提取通用函数 -- 万能查找
def find(func):  # 创建了钩子
    for item in list01:
        if func(item):  # 拉起钩子(执行条件)
            yield item


# for number in find(condition02):# 向钩子上挂条件
for number in find(lambda item: item % 2 == 0):  # 向钩子上挂条件
    print(number)

from common.iterable_tools import IterableHelper

# for number in IterableHelper.find(list01, condition01):
for number in IterableHelper.find_all(list01, lambda item: item % 2 == 0):
    print(number)

静态方法
1. 语法
(1) 定义:
@staticmethod
def 方法名称(参数列表):
方法体
(2) 调用:类名.方法名(参数列表)
不建议通过对象访问静态方法
2. 说明
(1) 使用@ staticmethod修饰的目的是该方法不需要隐式传参数。
(2) 静态方法不能访问实例成员和类成员
3. 作用:定义常用的工具函数。

"""
    common/
        iterable_tools.py
    可迭代对象工具
"""
class IterableHelper:
    """
        可迭代对象助手
    """
    @staticmethod
    def find_all(iterable, func):
        for item in iterable:
            if func(item):
                yield item
    
    @staticmethod
    def find_single(iterable,func):
        for emp in iterable:
            if func(emp):
                return emp

    @staticmethod
    def select(iterable,func):
        for emp in iterable:
            yield func(emp)
# for item in IterableHelper.find(列表,函数):
#  ...

练习一

"""
    练习1: 创建字典,遍历字典,打印索引/键/值
    练习2: 创建列表,将列表中大于10的数字,设置为0
"""
dict01 = {"a": "A", "b": "B"}
# (0, ('a', 'A'))
# for item in enumerate(dict01.items()):
for i, (k, v) in enumerate(dict01.items()):
    print(i, k, v)

list01 = [5, 6, 67, 8, 9, 9, 65, 43, 7]
for i, item in enumerate(list01):
    if item > 10:
        list01[i] = 0

print(list01)

练习二

# 练习:通过zip实现矩阵转置
list01 = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16],
]
# 固定行
# (1, 5, 9, 13)
# for item in zip(list01[0],list01[1],list01[2],list01[3]):
#     print(item)

# 使用*号将列表元素拆开
# for item in zip(*list01):
#     print(item)

# [(1, 5, 9, 13), (2, 6, 10, 14), (3, 7, 11, 15), (4, 8, 12, 16)]
# list02 = list(zip(*list01))
# print(list02)

# list02 = []
# for item in zip(*list01):
#      list02.append(list(item))

list02 = [list(item) for item in zip(*list01)]
print(list02)

练习三

# 练习1:在列表中获取所有整数,并计算它的平方.
# 练习2:在列表中获取所有大于10的小数.
# 要求:使用列表推导式,生成器表达式完成.
# 通过调试,体会差异.

list01 = [54, 65.5, True, "a", False, "b", 3, "c"]

# 练习1:
list02 = [item ** 2 for item in list01 if type(item) == int]
for number in list02:
    print(number)

generator02 = (item ** 2 for item in list01 if type(item) == int)
for number in generator02:
    print(number)

# 练习2:
list03 = [item for item in list01 if type(item) == float and item > 10]
for number in list03:
    print(number)

generator03 = (item for item in list01 if type(item) == float and item > 10)
for number in generator03:
    print(number)

练习四

"""
    将生成器函数,改写为生成器表达式
"""


class EmployeeModel:
    def __init__(self, eid=0, did=0, name="", money=0.0):
        self.eid = eid
        self.did = did
        self.name = name
        self.money = money


list_employee = [
    EmployeeModel(1001, 9003, "林", 13000),
    EmployeeModel(1002, 9003, "王", 16000),
    EmployeeModel(1003, 9003, "刘", 11000),
    EmployeeModel(1004, 9003, "冯", 17000),
    EmployeeModel(1005, 9003, "曹", 15000),
    EmployeeModel(1006, 9003, "魏", 12000),
]

# 1. 在list_employee中查找薪资大于等于15000的所有员工
employees_gt_15k = (emp for emp in list_employee if emp.money >= 15000)
for item in employees_gt_15k:
    print(item.__dict__)

# 3. 在list_employee中查找所有员工的姓名
names_by_employee = (emp.name for emp in list_employee)
for name in names_by_employee:
    print(name)

练习五

"""

"""
from common.iterable_tools import IterableHelper


class EmployeeModel:
    def __init__(self, eid=0, did=0, name="", money=0.0):
        self.eid = eid
        self.did = did
        self.name = name
        self.money = money


list_employee = [
    EmployeeModel(1001, 9003, "林", 13000),
    EmployeeModel(1002, 9005, "王", 16000),
    EmployeeModel(1003, 9003, "刘", 11000),
    EmployeeModel(1004, 9007, "冯", 17000),
    EmployeeModel(1005, 9005, "曹", 15000),
    EmployeeModel(1006, 9005, "魏", 12000),
]


# 1. 定义函数,在list_employee中查找薪资大于等于15000的所有员工
def find01():
    for emp in list_employee:
        if emp.money >= 15000:
            yield emp


# 2. 定义函数,在list_employee中查找部门编号是9005的所有员工
def find02():
    for emp in list_employee:
        if emp.did == 9005:
            yield emp


for item in find02():
    print(item.__dict__)


# ---------------------------
# 变化
def condition01(emp):
    return emp.money >= 15000


def condition02(emp):
    return emp.did == 9005


# 通用
def find(func):
    for emp in list_employee:
        # if emp.did == 9005:
        # if condition02(emp):
        if func(emp):
            yield emp

# 变化 + 通用
for item in find(condition02):
    print(item.__dict__)

for item in find(condition01):
    print(item.__dict__)


for item in IterableHelper.find_all(list_employee, condition01):
    print(item.__dict__)

练习六

"""
    exercise06.py
    练习:使用lambda代替condtion0x函数
"""
from common.iterable_tools import IterableHelper


class EmployeeModel:
    def __init__(self, eid=0, did=0, name="", money=0.0):
        self.eid = eid
        self.did = did
        self.name = name
        self.money = money


list_employee = [
    EmployeeModel(1001, 9003, "林", 13000),
    EmployeeModel(1002, 9005, "王", 16000),
    EmployeeModel(1003, 9003, "刘", 11000),
    EmployeeModel(1004, 9007, "冯", 17000),
    EmployeeModel(1005, 9005, "曹", 15000),
    EmployeeModel(1006, 9005, "魏", 12000),
]


# def condition01(emp):
#     return emp.money >= 15000
#
# def condition02(emp):
#     return emp.did == 9005

# 通用
def find(func):
    for emp in list_employee:
        if func(emp):
            yield emp


# 变化 + 通用
for item in find(lambda emp: emp.did == 9005):
    print(item.__dict__)

for item in find(lambda emp: emp.money >= 15000):
    print(item.__dict__)

for item in IterableHelper.find_all(list_employee, lambda emp: emp.money >= 15000):
    print(item.__dict__)

练习七

"""
    练习1需求:
        在员工列表中,查找姓名是"刘"的员工
        在员工列表中,查找员工编号是1005的员工

    练习2需求:
        在员工列表中,查找所有员工的姓名
        在员工列表中,查找所有员工的编号和薪资

    步骤
        1. 定义函数,完成需求.
        2. 将变化点定义为函数
           将通用代码定义为函数
        3. 通用函数使用参数隔离变化点
        4. 将通用函数移动到IterableHelper类中
        5. 在当前模块中调用通用函数(lambda)
"""
from common.iterable_tools import IterableHelper


class EmployeeModel:
    def __init__(self, eid=0, did=0, name="", money=0.0):
        self.eid = eid
        self.did = did
        self.name = name
        self.money = money


list_employee = [
    EmployeeModel(1001, 9003, "林", 13000),
    EmployeeModel(1002, 9005, "王", 16000),
    EmployeeModel(1003, 9003, "刘", 11000),
    EmployeeModel(1004, 9007, "冯", 17000),
    EmployeeModel(1005, 9005, "曹", 15000),
    EmployeeModel(1006, 9005, "魏", 12000),
]


def find01():
    for emp in list_employee:
        if emp.name == "刘":
            return emp


def find02():
    for emp in list_employee:
        if emp.eid == 1005:
            return emp


def condition01(emp):
    return emp.name == "刘"


def condition02(emp):
    return emp.eid == 1005


def find(func):
    for emp in list_employee:
        # if emp.eid == 1005:
        # if condition02(emp):
        if func(emp):
            return emp


emp01 = IterableHelper.find_single(list_employee, lambda emp: emp.name == "刘岳浩")
print(emp01.__dict__)


# 2.
def select01():
    for emp in list_employee:
        yield emp.name

def select02():
    for emp in list_employee:
        yield (emp.eid, emp.money)


def handle01(emp):
    return emp.name

def handle02(emp):
    return  (emp.eid, emp.money)

def select(func):
    for emp in list_employee:
        # yield (emp.eid, emp.money)
        # yield handle02(emp)
        yield func(emp)

for item in IterableHelper.select(list_employee,lambda emp:(emp.eid, emp.money)):
    print(item)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值