python3的itertools迭代器函数

# 受到函数式编程的启发,目的是保证迅速,并且告诉使用内存,进行迭代算法
# 与列表不同,基于迭代器可以提供更好的内存特性
# 因为只有在需要的时候才会生成,所以减少内存使用

import itertools
#itertools.count相当于无限迭代器
# def count(start=0, step=1):
#     # count(10) --> 10 11 12 13 14 ...
#     # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
#     n = start
#     while True:
#         yield n
#         n += step
# for i in itertools.count(start=0,step=1):
#      print(i)

#itertools.cycle相当于无限循环
# def cycle(iterable):
#     # cycle('ABCD') --> A B C D A B C D A B C D ...
#     saved = []
#     for element in iterable:
#         yield element
#         saved.append(element)
#     while saved:
#         for element in saved:
#               yield element
# for i in itertools.cycle('charlesval'):
#     print(i)

#itertools.repeat,把一个实例重复几次
# def repeat(object, times=None):
#     # repeat(10, 3) --> 10 10 10
#     if times is None:
#         while True:
#             yield object
#     else:
#         for i in range(times):
#             yield object
# def hello():
#     print('hello world')
# for i in itertools.repeat(hello,times=3):
#     i()

猜你喜欢

转载自blog.csdn.net/weixin_42557907/article/details/84038797