1. 程式人生 > >python3的itertools迭代器函式

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()