【发布时间】: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的迭代器。 -
为什么要合并
cartesianList?set是干什么用的? -
你应该把你的产品返回值变成如下列表:cartesianList= list(product(r, g, b))
-
你可能有一个无限源迭代器的产品,你真的不想消耗它来找到它的长度。
标签: python itertools python-3.6 cartesian-product