For Loop Throws Error但While Loop Doesnt

时间:2017-11-07 17:56:43

标签: python for-loop syntax while-loop

当我尝试在Python中使用for循环时,我无法理解我收到的错误。以下是导致该问题的循环:

list = ["1", "2", "3"]
numList = [int(i) for i in list]
product = 1
for i in numList:
   product = product * numList[i]

错误是:IndexError: list index out of range

我能够通过使用以下while循环解决问题:

list = ["1", "2", "3"]
numList = [int(i) for i in list]
product = 1
i = 0
while i < len(numList):
  product = product * numList[i]
  i += 1

导致错误的for循环有什么问题?

1 个答案:

答案 0 :(得分:3)

您使用列表值作为索引。你把索引与内容搞混了。

for i in numList:
    product = product*numList[i]

应该是

for i in numList:
    product = product * i

for i in range(len(numList)):
    product = product * numList[i]

将来,通过打印出您认为有问题的值来追踪这些问题。在这种情况下,错误消息告诉您索引超出范围,因此您应该尝试类似

    print i, type(i)

作为循环的第一个陈述。

另请注意,您可以稍微简化一下计算行:

    product *= i