对itertools的chain.from_iterable和chain()的更简化解释 [英] More simplified explanation of chain.from_iterable and chain() of itertools

查看:272
本文介绍了对itertools的chain.from_iterable和chain()的更简化解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能否对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']

如果ab在另一个序列中,则不必将它们拆包并传递给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屋!

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