gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:29:38 26 4
gpt4 key购买 nike

我阅读了另一篇文章来获取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) 这里

<小时/>为了 future 的访问者,更长的答案:

问:为什么我无法获取 itertools.product 的长度?
答:大多数 itertools 函数都会返回生成器,它们没有长度,因为它们是惰性计算的(并且可能是无限的)。

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

关于python - 为什么我无法获取 itertool.product 中的长度? Python 3.6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46288217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com