【问题标题】:How to use python itertools module如何使用 python itertools 模块
【发布时间】:2020-04-07 20:25:20
【问题描述】:

我有以下代码:

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

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

【问题讨论】:

标签: python functional-programming itertools


【解决方案1】:

您应该在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(iterable)

在这里,您传递了一个 single 迭代,其中包含其他迭代以从以下位置创建链:

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

【讨论】:

  • generator 是一种特定类型,而不是您可以迭代的一类类型。 chain 返回了一个 chain 的实例。
  • @chepner,非常感谢。你说得对。我已经编辑了答案。
【解决方案2】:

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

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

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

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

【讨论】:

    【解决方案3】:

    itertools.chain 返回一个迭代器,允许您通过__next__like a regular Python iterator 循环遍历for 中的值。

    例如:

    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 获取和可迭代(例如列表)的可迭代对象(例如其他列表)并依次迭代每个:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-07
      • 1970-01-01
      • 2013-08-04
      相关资源
      最近更新 更多