繁体   English   中英

如何使用python itertools模块

[英]How to use python itertools module

我有以下代码:

import itertools


x = ['Lebron' 'James']
y = ['is', 'the', 'goat']
z = ['is', 'not', 'the', 'goat']
itertools.chain(x, y)

我得到以下输出: itertools.chain at 0x104baab50

这个输出是什么意思? 我怎样才能看到该方法的结果?


那么下面的代码也是一样的:

itertools.chain.from_iterable([x,y])

我得到以下输出: itertools.chain at 0x104af7550

这是什么意思? 我怎样才能看到该方法的实际结果? 我不太确定这两种方法之间有什么区别。

itertools.chain返回一个迭代器,它允许您通过__next__等方式迭代for循环中的值,就像常规 Python 迭代器一样

例如:

In [3]: import itertools
   ...: x = ['Lebron', 'James']
   ...: y = ['is', 'the', 'goat']
   ...: z = ['is', 'not', 'the', 'goat']

In [4]: for thing in x:
   ...:     print('Thing is', thing)
   ...:
Thing is Lebron
Thing is James

In [5]: for thing in itertools.chain(x, y):
   ...:     print('Thing is', thing)
   ...:
Thing is Lebron
Thing is James
Thing is is
Thing is the
Thing is goat

from_iterable需要和 iterable (例如列表)的可迭代对象(例如其他列表)并依次迭代每个:

In [8]: for thing in itertools.chain.from_iterable([x, y]):
   ...:     print('Thing is', thing)
   ...:
Thing is Lebron
Thing is James
Thing is is
Thing is the
Thing is goat

简单地说, chain不是一个函数; 这是一种类型 与大多数类型一样,调用该类型时会返回该类型的实例。 实例chain(x,y)是可迭代的; 它首先从x产生元素,当它耗尽x ,它会从y产生元素。

chain.from_iterable是一个类方法; 它的定义实际上与

def from_iterable(itr):
    return chain(*itr)

假设您可以将*与任意可迭代对象一起使用。

您应该在Python Docs 中看到更多关于itertools模块的信息。

这个输出是什么意思? 我怎样才能看到该方法的结果?

返回了一个itertools.chain对象。 这是一个发电机。 例如,您可以通过以下方式查看结果(使用for循环遍历值):

for item in itertools.chain(x, y):
   print(item)

或者这样(从这个可迭代列表中创建一个列表):

print(list(itertools.chain(x, y)))


itertools.chain(*iterables)

在这里,您将传递几个可迭代对象以直接作为函数参数创建一个链:

itertools.chain(x, y)

itertools.chain.from_iterable(可迭代)

在这里,你路过它包含其他iterables从创建链单一迭代:

itertools.chain.from_iterable([x, y])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM