AI智能
改变未来

day011|python之函数2


函数03

[TOC]

1 迭代器

"""1、什么是迭代器?迭代器指的是迭代取值的工具迭代是一个重复的过程(不是单纯重复),每次重复都是基于上一次的结果进行的count = 1while count < 5:print(count)count += 12、为何要用迭代器?Ⅰ 为了找到一种通用的迭代取值的方案Ⅱ 节省内存3、如何用迭代器?可迭代对象内置有__iter__方法的类型都称之为可迭代对象但凡调用了__iter__方法,就会将该类型转换成迭代对象res = 值.__iter__()迭代器对象的特点:Ⅰ 内置有__next__方法Ⅱ 内置有__iter__方法(为了方便for循环)迭代器对象一定是可迭代对象可迭代对象不一定是迭代器对象4、迭代器优缺点总结:优点:Ⅰ 提供了一种不依赖索引的迭代取值方案Ⅱ 惰性计算,节省内存缺点:Ⅰ 取值麻烦Ⅱ 无法预测值的长度Ⅲ 一次性的"""# 可迭代的对象"hello".__iter__()              # 字符串[].__iter__()                   # 列表(11,).__iter__()                # 元组{"k1": 12, }.__iter__()         # 字典{11, 22}.__iter__()             # 集合f = open("a.txt", mode="wt")    # 文件f.__iter__()迭代器对象l = [11, 22, 33]iter_l = l.__iter__()print(iter_l.__next__())    # 11print(iter_l.__next__())    # 22print(iter_l.__next__())    # 33info = {\'name\': "ccc", "age": 18, "gender": \'male\'}iter_info = info.__iter__()print(iter_info.__next__())     # nameprint(iter_info.__next__())     # ageprint(iter_info.__next__())     # genderprint(iter_info.__next__())     # 抛出异常StopIteration迭代器的iter与本身print(iter_info.__iter__().__iter__().__iter__() is iter_info)  # Truel = [11, 222, 333, 444, 555]iter_l = iter(l)  # l.__iter__while True:try:print(next(iter_l))except StopIteration:break# 11# 222# 333# 444# 555l = {\'name\': "ccc", "age": 18, "gender": \'male\'}iter_l = iter(l)while True:try:print(next(iter_l))except StopIteration:breakprint(\'--------------------\')while True:try:print(next(iter_l))except StopIteration:break# name# age# gender# --------------------l = {\'name\': "ccc", "age": 18, "gender": \'male\'}iter_l = iter(l)while True:try:print(next(iter_l))except StopIteration:breakprint(\'--------------------\')iter_l = iter(l)while True:try:print(next(iter_l))except StopIteration:break# name# age# gender# --------------------# name# age# genderl = [11, 222, 333, 444, 555]iter_l = iter(l)for item in iter_l:print(item)print(\'====================\')for item in iter_l:print(item)# 11# 222# 333# 444# 555# ====================l = [11, 222, 333, 444, 555]iter_l = iter(l)for item in iter_l:print(item)print(\'====================\')iter_l = iter(l)for item in iter_l:print(item)# 11# 222# 333# 444# 555# ====================# 11# 222# 333# 444# 555for循环原理:1、调用可迭代对象.__iter__(),拿到一个迭代器对象2、调用next(迭代对象),将返回值赋值变量item3、循环往复,直到抛出异常Stopiteration,for会检测异常然后结束循环f = open(\'a.txt\', mode=\'rt\', encoding=\'utf-8\')for line in f:print(line)print(\'=======\')for line in f:print(line)f.close()# 111## 222## 333## 444# =======

2 生成器

"""1、生成器生成器就是一种自定义迭代器2、为何要用生成器为了省内存3、如何用生成器函数体内但凡出现yield关键字,调用函数将不会触发函数体代码的运行而是会返回一个生成器对象yield与return:相同点:在返回值角度用法一致不同点:yield可以返回多次值,return只能返回一次yield可以暂停函数,然后可以用next方法触发函数代码的运行->协程"""def func():print("1111")yield 1print("2222")yield 2print("3333")yield 3print("4444")g = func()          # 生成器本质就是一个迭代器print(g)            # <generator object func at 0x0000024D38B57900>res = next(g)       # 1111print(res)          # 1res = next(g)       # 2222print(res)          # 2res = next(g)       # 3333print(res)          # 3next(g)             # 4444 检测异常StopIterationdef func():print("1111")yield 1print("2222")yield 2print("3333")yield 3print("4444")g = func()print(g)for i in g:print(i)# <generator object func at 0x0000020C4D217900># 1111# 1# 2222# 2# 3333# 3# 4444def my_range(start, stop, step=1):while start < stop:yield startstart += stepfor i in my_range(0, 5, 2):print(i)# 0# 2# 4

3 三元表达式

res = "条件成立时返回的值" if "条件" else "条件不成立时返回的值"def max2(x, y):if x > y:return xelse:return yres = max2(11, 22)print(res)      # 22x = 11y = 22res = x if x > y else yprint(res)      # 22res = "ok" if 10 > 3 else "no"print(res)      # ok

4 生成式

1、列表生成式l = []for i in range(10):l.append(i)print(l)        # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]l = [i for i in range(10)]print(l)        # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]names = ["egon", "lxx_sb", "hxx_sb"]name = []for item in names:if item.endswith(\'sb\'):name.append(item)print(name)     # [\'lxx_sb\', \'hxx_sb\']names = ["egon", "lxx_sb", "hxx_sb"]name = [name for name in names if name.endswith("sb")]print(name)     # [\'lxx_sb\', \'hxx_sb\']2、字典生成式res = {i: i for i in range(5) if i > 2}print(res)      # {3: 3, 4: 4}3、集合生成式res = {i for i in range(5) if i > 2}print(res, type(res))       # {3, 4} <class \'set\'>4、生成器表达式res = (i for i in range(5))print(res)      # <generator object <genexpr> at 0x00000274941E7900>print(next(res))    # 0print(next(res))    # 1print(next(res))    # 2print(next(res))    # 3print(next(res))    # 4print(next(res))    # 抛出异常StopIterationwith open(\'a.txt\', mode=\'rt\', encoding=\'utf-8\') as f:res = 0for line in f:res += len(line)print(res)      # 15with open(\'a.txt\', mode=\'rt\', encoding=\'utf-8\') as f:res = sum(len(line) for line in f)print(res)      # 15

5 面向过程编程

面向过程编程思想:核心是过程二字过程就是做事的步骤,即先干啥、后干啥、再干啥所以基于该思想编写程序就好比在设计一条条流水线优点:复杂的问题流程化,进而简单化缺点:扩展性差
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » day011|python之函数2