itertools 的 chain.from_iterable 和 chain() 更简单的解释

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

您能否对itertools中的chain()chain.from_iterable这两种方法进行更简单的解释?

我搜索了知识库以及 python 文档,但我感到困惑。

我是 python 的新手,这就是为什么我要就这些问题提出更简单的解释。

谢谢!

您可以将序列链接成一个序列:

>>> 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

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

它通过迭代主序列的子序列来创建一个序列。这有时称为展平列表。如果您想扁平化列表列表的列表,则必须自己编写代码。 Stack Overflow 上有很多关于此的问题和答案。

我们可以通过查看 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
    ...

主要区别在于签名以及它们如何处理 iterable,这是可以迭代或循环的东西。

  • chain 接受可迭代对象,例如 "ABC", "DEF"[1, 2, 3], [7, 8, 9].
  • chain.from_iterable 接受一个可迭代对象,通常是一个嵌套的可迭代对象,例如"ABCDEF"[1, 2, 3, 7, 8, 9]。这有助于展平嵌套的可迭代对象。在 itertools recipes.
  • 中的 flatten 工具中查看它的直接实现

chain excepts a or more iterables as argument and returns iterator consists each item from iterables

喜欢下面

import itertools
for x in chain([1,2,3],(4,5,6)): #note can also accept different data types(list and tupe )
    print(x,end=' ')
#output
1 2 3 4 5 6 

chain.from_iterable 接受单个可迭代对象作为参数

for x in chain.from_iterable(['ABC']):  # the iterable argument with nested 
iterable(**'ABC' is again iterable**) 
    print(x,end=' ')
#output 
A B C

然而这不起作用

for x in chain.from_iterable([1,2,3]): 
    print(x,end=' ')
    #TypeError: 'int' object is not iterable