本文介绍了在itertools中chain和chain.from_iterable有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在互联网上找不到任何有效的例子,我可以看到它们之间的区别以及为什么选择其中一个。

I could not find any valid example on the internet where I can see the difference between them and why to choose one over the other.

推荐答案

第一个接受0个或多个参数,每个参数都是一个可迭代的,第二个参数接受一个参数,该参数可以产生迭代:

The first takes 0 or more arguments, each an iterable, the second one takes one argument which is expected to produce the iterables:

itertools.chain(list1, list2, list3)

iterables = [list1, list2, list3]
itertools.chain.from_iterable(iterables)

但是 iterables 可以是产生迭代的任何迭代器。

but iterables can be any iterator that yields the iterables.

def generate_iterables():
    for i in range(10):
        yield range(i)

itertools.chain.from_iterable(generate_iterables())

通常使用第二种形式一个方便的例子,但因为它懒洋洋地循环输入迭代,它也是链接无限数量的有限迭代器的唯一方法:

Using the second form is usually a case of convenience, but because it loops over the input iterables lazily, it is also the only way you can chain a infinite number of finite iterators:

def generate_iterables():
    while True:
        for i in range(5, 10):
            yield range(i)

itertools.chain.from_iterable(generate_iterables())

以上示例将给出你是一个迭代,它产生一个永远不会停止的循环数字模式,但永远不会消耗比单个 range()调用所需的内存更多的内存。

The above example will give you a iterable that yields a cyclic pattern of numbers that will never stop, but will never consume more memory than what a single range() call requires.

这篇关于在itertools中chain和chain.from_iterable有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:34