问题
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.
chainaccepts iterables, such as"ABC", "DEF"or[1, 2, 3], [7, 8, 9].chain.from_iterableaccepts 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 theflattentool found in the itertools recipes.
来源:https://stackoverflow.com/questions/43151271/more-simplified-explanation-of-chain-from-iterable-and-chain-of-itertools