【问题标题】:Why can I not get the length in itertool.product? Python 3.6为什么我无法在 itertool.product 中获得长度?蟒蛇 3.6
【发布时间】:2018-02-27 12:25:15
【问题描述】:

我阅读了另一篇文章以了解itertool.product() 的长度,但 OP 的问题从未得到解答。我不明白为什么会发生这个 len() 错误。代码如下:

from PIL import Image
import itertools

def function():
    rgb1 = [r,g,b]
    return itertools.product(rgb1, repeat=3)    #I added this

img = Image.open("anyImage.jpg")
r, g, b = img.split()

cartesianList = itertools.product([r,g,b], repeat=3)

for set in cartesianList:
    new_img = Image.merge("RGB", cartesianList)
    new_img.show()

输出是:

Traceback (most recent call last):
  File "C:/Users/Trevor/PycharmProjects/Pillow Test/test3.py", line 14, in <module>
    new_img = Image.merge("RGB", cartesianList)
  File "C:\Users\Trevor\AppData\Roaming\Python\Python36\site-packages\PIL\Image.py", line 2608, in merge
    if getmodebands(mode) != len(bands) or "*" in mode:
TypeError: object of type 'itertools.product' has no len()

【问题讨论】:

  • itertools.product 不返回列表。它返回一个不支持len的迭代器。
  • 为什么要合并cartesianListset 是干什么用的?
  • 你应该把你的产品返回值变成如下列表:cartesianList= list(product(r, g, b))
  • 你可能有一个无限源迭代器的产品,你真的不想消耗它来找到它的长度。

标签: python itertools python-3.6 cartesian-product


【解决方案1】:
for set in cartesianList:
    new_img = Image.merge("RGB", cartesianList)

你的意思是Image.merge("RGB", set)这里


为了未来的访客,更长的答案:

问:为什么我无法获得 itertools.product 的长度?
答:大多数 itertools 函数返回没有长度的生成器因为它们被懒惰地评估(并且可能是无限的)。

问:当我将 cartesianProduct 传递到 Image.merge 时,为什么会出现 itertools.product 错误?
答:您提供的 PIL 检查当您指定 Image.merge("RGB", [foo]) 时,它有 3 个通道,因此它调用 len(foo)。虽然这适用于cartesianList 中的每个set,但显然它不适用于cartesianList

【讨论】:

  • 这正是我错过的!现在很好用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 2017-03-28
  • 2012-03-25
  • 1970-01-01
  • 1970-01-01
  • 2012-09-14
相关资源
最近更新 更多