在以下程序中,我得到索引超出范围错误:
def evaluate(x, y):
result = 0
for i in x:
result += (x[i])*(y**i)
return result
答案 0 :(得分:2)
您已经循环遍历x
的所有值,无需再将其编入索引:
def evaluate(x, y):
result = 0
for i in x:
result += i * (y**i)
return result
比较以下两个:
>>> x = [3, 2]
>>> for i in x:
... print i
...
3
2
>>> for i in x:
... print x[i]
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IndexError: list index out of range
如果您希望i
成为x
的索引,请使用enumerate()
获取该索引:
def evaluate(x, y):
result = 0
for i, value in enumerate(x):
result += value * (y**i)
return result