itertools 模块学习笔记

itertools 模块学习笔记

# python itertools 模块学习
'''1、介绍
itertools 是python的迭代器模块,itertools提供的工具相当高效且节省内存。
使用这些工具,你将能够创建自己定制的迭代器用于高效率的循环。'''
# - 无限迭代器
#  itertools包自带了三个可以无限迭代的迭代器。
# 这意味着,当你使用他们时,你要的到达所需目标值就终止迭代而停止的迭代器,还是需要无限地迭代的迭代器。
from itertools import count, islice, cycle, chain, accumulate

'''class count(object):
    """
    Return a count object whose .__next__() method returns consecutive values.
        Equivalent to:
        def count(firstval=0, step=1):
            x = firstval
            while 1:
                yield x
                x += step
    """'''
# count(初始值=0, 步长值=1):count 迭代器会返回从传入的起始参数开始的均匀间隔的数值
for i in count(5, 3):
    if i > 20:
        break
    else:
        print(i)
# islice 的第二个参数控制何时停止迭代即”当迭代了 n 次之后停止“。
for i in islice(count(8), 5):
    print(i)

# cycle: 从iterable返回元素,直到元素用尽。然后无限期地重复该序列。
""" Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely. """
count = 0
for c in cycle('abc'):
    if count > 5:
        break
    else:
        print(c)
        count += 1

# 当需要合并多个列表时候可以使用chain
my_list = ['car', 'air']
numbers = list(range(4))
str = ['list', 'string']
# extend合并列表方法
# my_list.extend(numbers)
# my_list.extend(str)
# print(my_list)

# my_list += numbers + str
# print(my_list)

# 当需要合并多个列表时候
# chain 迭代器能够将多个可迭代对象合并成一个更长的可迭代对象
new_list = list(chain(my_list, numbers, str))
print(new_list)


# 当多个值累计求和时候(求值结果作为下一次使用  累加、累积)
# accumulate 返回一系列累积和(或其他二进制函数结果)
""" Return series of accumulated sums (or other binary function results). """
# accumulate(一参为可迭代对象,[二参可为函数])
import operator

dataList = list(accumulate(range(1, 10), operator.mul))
print(dataList)  # [1, 2, 6, 24, 120, 720]

print(list(accumulate(range(1, 8))))
'''
1	   2	   3     4	     5	     6      7	     8     	9
	=A1+B1	=B2+C1	=C2+D1	=D2+E1	=E2+F1	=F2+G1	=G2+H1	=H2+I1
=1*A1	=A3*B1	=B3*C1	=C3*D1	=D3*E1	=E3*F1	=F3*G1	=G3*H1	=H3*I1
'''

`

posted @ 2022-02-16 13:18  zechariah1  阅读(41)  评论(0编辑  收藏  举报