对itertools的chain.from_iterable和chain()的更简化解释 [英] More simplified explanation of chain.from_iterable and chain() of itertools
问题描述
您能否对itertools
中的chain()
和chain.from_iterable
这两种方法进行更简单的说明?
Can you give a more simplified explanation of these two methods chain()
and chain.from_iterable
from itertools
?
我已经搜索了知识库以及python文档,但是我很困惑.
I have searched the knowledge base and as well the python documentation but i got confused.
我是python的新手,这就是为什么我要对此进行更简化的解释.
I am new to python that's why I am asking a more simplified explanation regarding these.
谢谢!
推荐答案
您可以将序列链接成单个序列:
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']
如果a
和b
在另一个序列中,则不必将它们拆包并传递给chain
,您可以将整个序列传递给from_iterable
:
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.
这篇关于对itertools的chain.from_iterable和chain()的更简化解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!