“'生成器'对象不可下标"错误 [英] "'generator' object is not subscriptable" error
问题描述
尝试解决Project Euler问题11时,为什么从代码的第5行出现此错误?
Why am I getting this error, from line 5 of my code, when attempting to solve Project Euler Problem 11?
for x in matrix:
p = 0
for y in x:
if p < 17:
currentProduct = int(y) * int(x[p + 1]) * int(x[p + 2]) * int(x[p + 3])
if currentProduct > highestProduct:
print(currentProduct)
highestProduct = currentProduct
else:
break
p += 1
'generator' object is not subscriptable
推荐答案
您的x
值是一个生成器对象,它是一个 next(x)
.
Your x
value is is a generator object, which is an Iterator
: it generates values in order, as they are requested by a for
loop or by calling next(x)
.
您正在尝试访问它,就像它是列表或其他 Sequence
类型,它使您可以按x[p + 1]
的索引访问任意元素.
You are trying to access it as though it were a list or other Sequence
type, which let you access arbitrary elements by index as x[p + 1]
.
如果要按索引从生成器的输出中查找值,则可能需要将其转换为列表:
If you want to look up values from your generator's output by index, you may want to convert it to a list:
x = list(x)
这可以解决您的问题,并且适合大多数情况.但是,这需要一次生成并保存所有值,因此,如果要处理的值列表过长或无限,或者值很大,则可能会失败.
This solves your problem, and is suitable in most cases. However, this requires generating and saving all of the values at once, so it can fail if you're dealing with an extremely long or infinite list of values, or the values are extremely large.
如果您只需要生成器中的单个值,则可以改用 itertools.islice(x, p)
放弃第一个p
值,然后next(...)
放弃您需要的值.这样一来,您就不必在内存中保留多个项目或计算超出您要查找的项目的值.
If you just needed a single value from the generator, you could instead use itertools.islice(x, p)
to discard the first p
values, then next(...)
to take the one you need. This eliminate the need to hold multiple items in memory or compute values beyond the one you're looking for.
import itertools
result = next(itertools.islice(x, p))
这篇关于“'生成器'对象不可下标"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!