chain(* iterable)与chain.from_iterable(iterable)之间的区别 [英] Difference between chain(*iterable) vs chain.from_iterable(iterable)

查看:307
本文介绍了chain(* iterable)与chain.from_iterable(iterable)之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的被itertools中所有有趣的迭代器所吸引,但是我感到困惑的是这两个函数之间的区别以及chain.from_iterable存在的原因.

I have been really fascinated by all the interesting iterators in itertools, but one confusion I have had is the difference between these two functions and why chain.from_iterable exists.

from itertools import chain

def foo(n):
    for i in range(n):
        yield [i, i**2]

chain(*foo(5))

chain.from_iterable(foo(5))

这两个功能有什么区别?

What is the difference between the two functions?

推荐答案

前者只能处理不可打包的可迭代对象.后者可以处理无法完全解包的可迭代对象,例如无限生成器.

The former can only handle unpackable iterables. The latter can handle iterables that cannot be fully unpacked, such as infinite generators.

考虑

>>> from itertools import chain
>>> def inf():
...     i=0
...     while True:
...         i += 1
...         yield (i, i)
... 
>>> x=inf()
>>> y=chain.from_iterable(x)
>>> z=chain(*x)
<hangs forever>

此外,仅拆箱操作是一项急于进行的前期成本活动,因此,如果您的迭代项目具有您希望懒惰地评估的效果,则from_iterable是您的最佳选择.

Furthermore, just the act of unpacking is an eager, up-front-cost activity, so if your iterable has effects you want to evaluate lazily, from_iterable is your best option.

这篇关于chain(* iterable)与chain.from_iterable(iterable)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆