生成器和迭代器练习案例
1、实现enumerate函数
def enumerate_generator(iterable): for i in range(len(iterable)): yield i,iterable[i] gen_e = enumerate_generator(['a','b','c','d']) for e in gen_e: print(e)
运行结果:
(0, 'a') (1, 'b') (2, 'c') (3, 'd')
2、实现zip函数
def zip_generator(*args): len_list = [] for i in args: len_list.append(len(i)) for n in range(min(len_list)): t = () for i in args: t += (i[n],) yield t gen_z = zip_generator([1,2,3,4],('a','b','c','d','e'),['A','B','C']) for z in gen_z: print(z)
运行结果:
(1, 'a', 'A') (2, 'b', 'B') (3, 'c', 'C')
3、不使用for循环,遍历列表[1,2,3,4,5,6,7,8,9,10]
a_list = [1,2,3,4,5,6,7,8,9,10] iter_list = a_list.__iter__() #变成迭代器 while True: try: res = next(iter_list) except: break else: print(res)
运行结果:
1 2 3 4 5 6 7 8 9 10