day011|python之函数2

函数03

1 迭代器

"""
1、什么是迭代器?
    迭代器指的是迭代取值的工具
    迭代是一个重复的过程(不是单纯重复),每次重复都是基于上一次的结果进行的

    count = 1
    while count < 5:
        print(count)
        count += 1

2、为何要用迭代器?
    Ⅰ 为了找到一种通用的迭代取值的方案
    Ⅱ 节省内存

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__())    # 11
print(iter_l.__next__())    # 22
print(iter_l.__next__())    # 33

info = {'name': "ccc", "age": 18, "gender": 'male'}
iter_info = info.__iter__()
print(iter_info.__next__())     # name
print(iter_info.__next__())     # age
print(iter_info.__next__())     # gender
print(iter_info.__next__())     # 抛出异常StopIteration


迭代器的iter与本身
print(iter_info.__iter__().__iter__().__iter__() is iter_info)  # True


l = [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
# 555

l = {'name': "ccc", "age": 18, "gender": 'male'}
iter_l = iter(l)
while True:
    try:
        print(next(iter_l))
    except StopIteration:
        break

print('--------------------')
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:
        break

print('--------------------')
iter_l = iter(l)
while True:
    try:
        print(next(iter_l))
    except StopIteration:
        break
# name
# age
# gender
# --------------------
# name
# age
# gender

l = [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
# 555

for循环原理:
1、调用可迭代对象.__iter__(),拿到一个迭代器对象
2、调用next(迭代对象),将返回值赋值变量item
3、循环往复,直到抛出异常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 1
    print("2222")
    yield 2
    print("3333")
    yield 3
    print("4444")

g = func()          # 生成器本质就是一个迭代器
print(g)            # <generator object func at 0x0000024D38B57900>

res = next(g)       # 1111
print(res)          # 1

res = next(g)       # 2222
print(res)          # 2

res = next(g)       # 3333
print(res)          # 3

next(g)             # 4444 检测异常StopIteration


def func():
    print("1111")
    yield 1
    print("2222")
    yield 2
    print("3333")
    yield 3
    print("4444")

g = func()
print(g)
for i in g:
    print(i)
# <generator object func at 0x0000020C4D217900>
# 1111
# 1
# 2222
# 2
# 3333
# 3
# 4444


def my_range(start, stop, step=1):
    while start < stop:
        yield start
        start += step

for i in my_range(0, 5, 2):
    print(i)
# 0
# 2
# 4

3 三元表达式

res = "条件成立时返回的值" if "条件" else "条件不成立时返回的值"

def max2(x, y):
    if x > y:
        return x
    else:
        return y
res = max2(11, 22)
print(res)      # 22


x = 11
y = 22
res = x if x > y else y
print(res)      # 22


res = "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))    # 0
print(next(res))    # 1
print(next(res))    # 2
print(next(res))    # 3
print(next(res))    # 4
print(next(res))    # 抛出异常StopIteration


with open('a.txt', mode='rt', encoding='utf-8') as f:
    res = 0
    for line in f:
        res += len(line)
    print(res)      # 15


with open('a.txt', mode='rt', encoding='utf-8') as f:
    res = sum(len(line) for line in f)
    print(res)      # 15

5 面向过程编程

面向过程编程思想:
    核心是过程二字
    过程就是做事的步骤,即先干啥、后干啥、再干啥
    所以基于该思想编写程序就好比在设计一条条流水线

    优点:复杂的问题流程化,进而简单化
    缺点:扩展性差
posted @ 2020-12-08 16:34  drrug  阅读(58)  评论(0编辑  收藏  举报