迭代器,生成器

1,什么是迭代器

    迭代:更新换代(重复)的过程,每次的迭代都必须基于上一次的结果

    迭代器:迭代取值的工具

   迭代器给你提供了一种不依赖于索引取值的方式

 

基本数据类型中

    是可迭代对象的有

        str list tuple dict set 

        文件对象(执行内置的__iter__之后还是本身 没有任何变化):文件对象本身就是迭代器对象

 

2,迭代器取值

  

迭代器对象

    1.内置有__iter__方法

    2.内置有__next__方法

    ps:迭代器一定是可迭代对象

    而可迭代对象不一定是迭代器对象

 

#迭代器的取值

l = [1, 2, 3, 4, 5]

iter_l = l.__iter__()

print(iter_l.__next__())
print(iter_l.__next__())
print(iter_l.__next__())

d = {'name':'jason', 'password':'123'}
#将可迭代对象d 转换成迭代器对象

iter_d = d.__iter__()

#迭代器对象的取值,必须用_next_()方法

print(iter_d.__next__())

print(iter_d.__next__())#取值完了报错
'''
迭代器对象无论执行多少次_iter_方法得到的还是迭代器对象本身.

'''
#异常处理

# while True:
#     try:
#         pass
#     except error


"""
迭代器取值的特点
    1.只能往后依次取值


"""

#文件对象取值的方法:

f = open('aaa.txt', 'r', encoding='utf-8')

iter_f = f.__iter__()

print(iter_f.__next__())
print(iter_f.__next__())
print(iter_f.__next__())
print(iter_f.__next__())
print(iter_f.__next__())
 1 """
 2 迭代器对象
 3     1.内置有__iter__方法
 4     2.内置有__next__方法
 5     ps:迭代器一定是可迭代对象
 6     而可迭代对象不一定是迭代器对象
 7 """
 8 
 9 
10 
11 # l = [1,2,3,4]
12 # # 生成一个迭代器对象
13 # iter_l = l.__iter__()
14 #
15 # # 迭代器取值 调用__next__
16 # print(iter_l.__next__())
17 # print(iter_l.__next__())
18 # print(iter_l.__next__())
19 # print(iter_l.__next__())
20 # print(iter_l.__next__())  # 如果取完了 直接报错
21 
22 
23 # d = {'name':'jason','password':'123','hobby':'泡m'}
24 # # 将可迭代对象d转换成迭代器对象
25 # iter_d = d.__iter__()
26 # # 迭代器对象的取值 必须用__next__
27 # print(iter_d.__next__())
28 # print(iter_d.__next__())
29 # print(iter_d.__next__())
30 # print(iter_d.__next__())  # 取完了 报错StopIteration
31 
32 f1 = open('xxx.txt','r',encoding='utf-8')
33 # 调用f1内置的__iter__方法
34 # iter_f = f1.__iter__()
35 # print(iter_f is f1)
36 """
37 迭代器对象无论执行多少次__iter__方法得到的还是迭代器对象本身(******)
38 """
39 # print(f1 is f1.__iter__().__iter__().__iter__().__iter__())
40 """
41 问:__iter__方法就是用来帮我们生成迭代器对象
42 而文件对象本身就是迭代器对象,为什么还内置有__iter__方法???
43 """
44 
45 
46 
47 
48 
49 d = {'name':'jason','password':'123','hobby':'泡m'}
50 # iter_d = d.__iter__()
51 
52 
53 # print(d.__iter__().__next__())
54 # print(d.__iter__().__next__())
55 # print(d.__iter__().__next__())
56 
57 # print(iter_d.__next__())
58 # print(iter_d.__next__())
59 # print(iter_d.__next__())
60 # print(iter_d.__next__())
61 
62 # 异常处理
63 # while True:
64 #     try:
65 #         print(iter_d.__next__())
66 #     except StopIteration:
67 #         # print('老母猪生不动了')
68 #         break
69 
70 
71 # f = open('xxx.txt','r',encoding='utf-8')
72 # iter_f = f.__iter__()
73 # print(iter_f.__next__())
74 # print(iter_f.__next__())
75 # print(iter_f.__next__())
76 # print(iter_f.__next__())
77 # print(iter_f.__next__())
78 
79 
80 
81 """
82 迭代器取值的特点
83     1.只能往后依次取 不能后退
84 
85 """
View Code

3,for循环的本质

d = {'nmae':'egon', 'pwd':'123', 'hobby':'piao'}

'''
for循环后面的 in 跟的是一个可迭代对象

for 循环后面的 in 可以跟一个可迭代对象,也可以使迭代器对象.

for循环的本质


    1,将 in 后面的对象调用 _iter_() 方法转换成迭代器对对象
    2,调用_next_迭代取值
    3,内部有异常捕获StopIteration,当_next_报错,自动结束循环.
'''

'''
可迭代对象:内助有_iter_ 方法
迭代器对象:既有内置_iter_也有内置_next_ 方法

迭代取值:

    优点
        1.不依赖于索引取值
        2,内存中永远只占一份空间,不会导致内存溢出
        
    缺点
        1,不能获取指定的元素
        2, 取值完了会报错
'''

l = [1, 2, 3, 4]
res = map(lambda x: x+1, l) # 语法 map(函数,可迭代对象)
print(res.__next__())
print(res.__next__())
print(res.__next__())
print(res.__next__())
print(res.__next__())
 1 d = {'name':'jason','password':'123','hobby':'泡m'}
 2 # for i in d:
 3 #     print(i)
 4 # for循环后面的in关键 跟的是一个可迭代对象
 5 """
 6 for循环内部的本质
 7     1.将in后面的对象调用__iter__转换成迭代器对象
 8     2.调用__next__迭代取值
 9     3.内部有异常捕获StopIteration,当__next__报这个错 自动结束循环
10 """
11 # for i in 1:
12 #     pass
13 # iter(1)
14 
15 
16 """
17 可迭代对象:内置有__iter__方法的
18 迭代器对象:既内置有__iter__也内置有__next__方法
19 
20 迭代取值:
21     优点
22         1.不依赖于索引取值
23         2.内存中永远只占一份空间,不会导致内存溢出
24     
25     缺点
26         1.不能够获取指定的元素
27         2.取完之后会报StopIteration错
28 
29 """
30 # l = [1,2,3,4]
31 # res = map(lambda x:x+1,l)
32 # print(map(lambda x:x+1,l))
33 # print(res.__next__())
34 # print(res.__next__())
35 # print(res.__next__())
36 
37 
38 l1 = [1,2,3,4,5]
39 l2 = ['a','b','c']
40 print(zip(l1,l2))
View Code

4,生成器

'''
生成器本质就是迭代器

'''

#如果函数中有 yield 的关键字,加括号执行函数名的时候,并不会执行函数体代码

#yield 后面跟的值就是调用迭代器_next_方法返回的值

#yield 可以返回一个值,也可以返回多个值 元祖的形式.


#生成器传值

def my_range(start,end,bc):
    while start < end:
        yield start
        start += bc

for i in my_range(1,10,2):
    print(i)
 1 """
 2 生成器:用户自定义的迭代器,本质就是迭代器
 3 
 4 """
 5 # def func():
 6 #     print('first')
 7 #     yield  666  # 函数内如果有yield关键字,那么加括号执行函数的时候并不会触发函数体代码的运行
 8 #     print('second')
 9 #     yield  777
10 #     print('third')
11 #     yield  888
12 #     print('forth')
13 #     yield
14 #     yield
15 # # yield后面跟的值就是调用迭代器__next__方法你能得到的值
16 # # yield既可以返回一个值也可以返回多个值 并且多个值也是按照元组的形式返回
17 # g = func()  # 生成器初始化:将函数变成迭代器
18 # print(g)
19 # print(g.__next__())
20 # print(g.__next__())
21 # print(g.__next__())
22 # print(g.__next__())
23 # print(g.__next__())
24 
25 
26 
27 # print(range(1,10))
28 
29 # for i in range(1,10,2):
30 #     print(i)
31 
32 def my_range(start,end,step=1):
33     while start < end:
34         yield start
35         start += step
36 
37 
38 for j in my_range(1,100,2):
39     print(j)
View Code

5, yield 的表达式形式

 1 # yield支持外界为其传参
 2 def dog(name):
 3     print('%s 准备开吃'%name)
 4     while True:
 5         food = yield
 6         print('%s 吃了 %s'%(name,food))
 7 # def index():
 8 #     pass
 9 
10 # 当函数内有yield关键字的时候,调用该函数不会执行函数体代码
11 # 而是将函数变成生成器
12 # g = dog('egon')
13 # g.__next__()  # 必须先将代码运行至yield 才能够为其传值
14 # g.send('狗不理包子')  # 给yield左边的变量传参  触发了__next__方法
15 # g.send('饺子')
16 
17 """
18 yield
19     1.帮你提供了一种自定义生成器方式
20     2.会帮你将函数的运行状态暂停住
21     3.可以返回值
22 
23 与return之间异同点
24     相同点:都可以返回值,并且都可以返回多个
25     不同点:
26         yield可以返回多次值,而return只能返回一次函数立即结束
27         yield还可以接受外部传入的值
28 """
View Code

6, 生成器表达式

# 列表生成式
# res = [i for i in range(1,10) if i != 4]
# print(res)

# 生成器表达式
'''
生成器不会主动执行代码,必须通过_next_ 触发执行.
'''
# res1 = (i for i in range(1,10) if i != 4)
#
# print(res1)
#
# print(res1.__next__())

#计算文件aaa.txt字符的总长度

with open('aaa.txt', 'r', encoding='utf-8') as f:
    res_f = (len(line) for line in f)
    print(sum(res_f))
    
 1 # 列表生成式
 2 # res = [i for i in range(1,10) if i != 4]
 3 # print(res)
 4 
 5 # res = (i for i in range(1,100000000) if i != 4)  # 生成器表达式
 6 # print(res)
 7 # """
 8 # 生成器不会主动执行任何一行代码
 9 # 必须通过__next__触发代码的运行
10 # """
11 # print(res.__next__())
12 # print(res.__next__())
13 # print(res.__next__())
14 # print(res.__next__())
15 
16 
17 # 占内存
18 # f = open('xxx.txt','r',encoding='utf-8')
19 # data = f.read()
20 # print(len(data))
21 # f.close()
22 
23 
24 # with open('xxx.txt','r',encoding='utf-8') as f:
25 #     # n = 0
26 #     # for line in f:
27 #     #     n += len(line)
28 #     # print(n)
29 #     g = (len(line) for line in f)
30 #     # print(g.__next__())
31 #     # print(g.__next__())
32 #     # print(g.__next__())
33 #     # print(g.__next__())
34 #     print(sum(g))
35 
36 
37 
38 def add(n,i):
39     return n+i
40 def test():
41     for i in range(4):
42         yield i
43 g=test()
44 
45 for n in [1,10]:
46     g=(add(n,i) for i in g)
47     # 第一次for循环g=(add(n,i) for i in test())
48 
49     # 第二次for循环g=(add(n,i) for i in (add(n,i) for i in test()))
50 print(n)
51 res=list(g)
52 
53 """
54 for i in (add(10,i) for i in test()):  会执行所有的生成器内部的代码
55     add(n,i)
56 """
57 
58 
59 
60 
61 #A. res=[10,11,12,13]
62 #B. res=[11,12,13,14]
63 #C. res=[20,21,22,23]  答案
64 #D. res=[21,22,23,24]
View Code

7, 常用内置方法;

  1 # print(abs(-11.11))  # 求绝对值
  2 # l = [0,1,0]
  3 # print(all(l))  # 只要有一个为False就返回False
  4 # print(any(l))  # 只要有一个位True就返回True
  5 def index():
  6 
  7     username = '我是局部名称空间里面的username'
  8     # print(locals())  # 当前语句在哪个位置 就会返回哪个位置所存储的所有的名字
  9     print(globals())  # 无论在哪 查看的都是全局名称空间
 10 # index()
 11 # print(bin(10))
 12 # print(oct(10))
 13 # print(hex(10))
 14 # print(int('0b1010',2))
 15 
 16 # print(bool(1))
 17 # print(bool(0))
 18 
 19 
 20 # s = 'hello'
 21 # print(s.encode('utf-8'))
 22 # print(bytes(s,encoding='utf-8'))
 23 
 24 # 可调用的(可以加括号执行相应功能的)
 25 # l = [1,2,3]
 26 # def index():
 27 #     pass
 28 # print(callable(l))
 29 # print(callable(index))
 30 
 31 
 32 
 33 
 34 
 35 # print(chr(97))  # 将数字转换成ascii码表对应的字符
 36 # print(ord('a'))  # 将字符按照ascii表转成对应的数字
 37 
 38 """
 39 面向对象需要学习的方法
 40 classmethod
 41 delattr
 42 getattr
 43 hasattr
 44 issubclass
 45 property
 46 repr
 47 setattr
 48 super
 49 staticmethod
 50 """
 51 # dir获取当前对象名称空间里面的名字
 52 # l = [1,2,3]
 53 # print(dir(l))
 54 #
 55 # import test
 56 # print(dir(test))
 57 # print(test.name)
 58 
 59 # divmod  分页器
 60 
 61 # print(divmod(101,10))
 62 # total_num,more = divmod(900,11)
 63 # if more:
 64 #     total_num += 1
 65 # print('总页数:',total_num)
 66 
 67 # enumerate 枚举
 68 # l = ['a','b']
 69 # for i,j in enumerate(l,1):
 70 #     print(i,j)
 71 
 72 # eval  exec
 73 s = """
 74 print('hello baby~')
 75 x = 1
 76 y = 2
 77 print(x + y)
 78 
 79 """
 80 # eval(s)
 81 # exec(s)
 82 
 83 # eval不支持逻辑代码,只支持一些简单的python代码
 84 s1 = """
 85 print(1 + 2)
 86 for i in range(10):
 87     print(i)
 88 """
 89 # eval(s1)
 90 # exec(s1)
 91 
 92 
 93 # name = 'jason'
 94 # s2 = """
 95 # name
 96 # """
 97 # print(eval(s2))
 98 
 99 # format 三种玩法
100 # {}占位
101 # {index} 索引
102 # {name} 指名道姓
103 
104 # print(globals())
105 def login():
106     """
107     一起嗨皮
108     :return:
109     """
110 # print(help(login))
111 
112 # isinstance 后面统一改方法判断对象是否属于某个数据类型
113 # n = 1
114 # print(type(n))
115 # print(isinstance(n,list))  # 判断对象是否属于某个数据类型
116 
117 # print(pow(2,3))
118 
119 
120 # print(round(3.4))
View Code

8, 面向过程编程:

 1 """
 2 面向过程编程:就类似于设计一条流水线
 3     好处:
 4         将复杂的问题流程化 从而简单化
 5     坏处:
 6         可扩展性较差   一旦需要修改 整体都会受到影响
 7 """
 8 # 注册功能
 9 # 1.获取用户输入
10 def get_info():
11     while True:
12         username = input(">>>:").strip()
13         if not username.isalpha():  # 判断字符串不能包含数字
14             print('不能包含数字')
15             continue
16         password = input('>>>:').strip()
17         confirm_password = input("confirm>>>:").strip()
18         if password == confirm_password:
19             d = {
20                 '1':'user',
21                 '2':'admin'
22             }
23             while True:
24                 print("""
25                     1 普通用户
26                     2 管理员
27                 """)
28                 choice = input('please choice user type to register>>>:').strip()
29                 if choice not in d:continue
30                 user_type = d.get(choice)
31                 operate_data(username,password,user_type)
32                 break
33         else:
34             print('两次密码不一致')
35 
36 # 2.处理用户信息
37 def operate_data(username,password,user_type):
38     # jason|123
39     res = '%s|%s|%s\n'%(username,password,user_type)
40     save_data(res,'userinfo.txt')
41 
42 # 3.存储到文件中
43 def save_data(res,file_name):
44     with open(file_name,'a',encoding='utf-8') as f:
45         f.write(res)
46 
47 def register():
48     get_info()
49 
50 register()
View Code

 

 

 

转载于:https://www.cnblogs.com/chendaodeng/p/11191615.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值