Python设计模式(十六)【迭代器模式】

来源:互联网 发布:linux系统入门教程 编辑:程序博客网 时间:2024/06/05 18:43

人只要不失去方向,就不会失去自己!

"""Implementation of the iterator pattern with a generator一个生成器实现迭代器模式"""from __future__ import print_functiondef count_to(count):    """由数字编号计数,最多五个"""    numbers = ["one", "two", "three", "four", "five"]    # 枚举()返回一个包含计数的元组(默认从0开始)从遍历序列获得值    for pos, number in zip(range(count), numbers):        yield number# 测试生成器count_to_two = lambda: count_to(2)count_to_five = lambda: count_to(5)print('数到2...')for number in count_to_two():    print(number, end=' ')print()print('数到5...')for number in count_to_five():    print(number, end=' ')print()

运行结果如图:

这里写图片描述

0 0
原创粉丝点击