1

在以下程序中,我得到了索引超出范围错误:

def evaluate(x, y):
    result = 0
    for i in x:
        result += (x[i])*(y**i)
    return result
4

1 回答 1

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
于 2012-10-20T16:31:51.777 回答