编程语言
首页 > 编程语言> > Itertools in python

Itertools in python

作者:互联网

Itertools in python

  1. Itertools:Functions creating iterators for efficient looping(是一系列函数,用来创建迭代器,是为了更有效的循环。
  2. 迭代器:可以看成是一个for循环的封装。有无限循环和有限循环
    举个例子:
// 无限循环迭代器cycle
cycle('ABCD') --> A B C D A B C D ...
  1. 对于Itertool functions,它是用来创建和返回一个迭代器。
# itertools.chain(*iterables) 创建一个迭代器
def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element
# classmethod chain.from_iterable(iterable) 类似chain()
def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
       	# yield 相当于return, 只是它返回的是一种iterator
            yield element
# output: [{'a': 0}, {'b': 1}, {'c': 2}, {'d': 3}]
ite = itertools.chain.from_iterable(
	[
		[{'a':0}, {'b':1}], 
		[{'c':2}], 
		[{'d':3}]
	]
)
print(list(ite)) 

参考文献

https://docs.python.org/zh-cn/3/library/itertools.html#itertools.chain

标签:chain,迭代,python,itertools,element,Itertools,iterables,iterable
来源: https://blog.csdn.net/qq_35470686/article/details/88092740