python:索引在一个简单的程序中超出范围

时间:2012-10-20 16:30:24

标签: python

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

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

1 个答案:

答案 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