为什么我无法获取 itertool.product 中的长度? Python 3.6

Why can I not get the length in itertool.product? Python 3.6

我阅读了另一个 post 以获得 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()
for set in cartesianList:
    new_img = Image.merge("RGB", cartesianList)

很确定你指的是 Image.merge("RGB", set) 这里


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

问:为什么我无法获取itertools.product的长度?
A: 大多数 itertools 函数 return 生成器,它们没有长度,因为它们是延迟计算的(并且可能是无限的)。

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