More simplified explanation of chain.from_iterable and chain() of itertools

我只是一个虾纸丫 提交于 2019-12-24 09:37:56

问题


Can you give a more simplified explanation of these two methods chain() and chain.from_iterable from itertools?

I have searched the knowledge base and as well the python documentation but i got confused.

I am new to python that's why I am asking a more simplified explanation regarding these.

Thanks!


回答1:


You can chain sequences to make a single sequence:

>>> from itertools import chain

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> list(chain(a, b))
[1, 2, 3, 'a', 'b', 'c']

If a and b are in another sequence, instead of having to unpack them and pass them to chain you can pass the whole sequence to from_iterable:

>>> c = [a, b]
>>> list(chain.from_iterable(c))
[1, 2, 3, 'a', 'b', 'c']

It creates a sequence by iterating over the sub-sequences of your main sequence. This is sometimes called flattening a list. If you want to flatten lists of lists of lists, you'll have to code that yourself. There are plenty of questions and answers about that on Stack Overflow.




回答2:


We can learn about the difference between these two tools by looking at the docs.

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    ...

def from_iterable(iterable):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    ...

The key difference is in the signatures and how they handle an iterable, which is something that can be iterated or looped over.

  • chain accepts iterables, such as "ABC", "DEF" or [1, 2, 3], [7, 8, 9].
  • chain.from_iterable accepts one iterable, often a nested iterable, e.g. "ABCDEF" or [1, 2, 3, 7, 8, 9]. This is helpful for a flattening nested iterables. See its direct implementation in the flatten tool found in the itertools recipes.


来源:https://stackoverflow.com/questions/43151271/more-simplified-explanation-of-chain-from-iterable-and-chain-of-itertools

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!