【问题标题】:For Loop Throws Error but While Loop DoesntFor 循环抛出错误,但 While 循环没有
【发布时间】:2017-11-07 17:56:43
【问题描述】:

当我尝试在 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 循环有什么问题导致错误?

【问题讨论】:

  • 您正在用 for 循环案例中的内容为列表编制索引。 3 不是有效索引。
  • 也许尝试在每种情况下打印i 的值。
  • 应该是product = product * i,因为i 是列表中的数字。给它一个更好的名字。
  • 数组在 Python 中为 0,您将 i 循环为 1,2,3,列表数组只有索引 0,1,2
  • 感谢您的回复。 list 中的项目并不总是与索引相同。例如:list = ["15", "2", "129"]。我曾经打印出i,但它一定是在一个迭代中,我在代码中有一个while循环而不是for循环。

标签: python for-loop syntax while-loop


【解决方案1】:

您使用列表值作为索引。您将索引与内容混淆了。

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

【讨论】:

  • 感谢您对for 循环的帮助。我没有意识到 for i in numList 行不会从 0 开始,因为 list 索引从 0 开始。关于 product *=i 我不能这样做,因为 list 中的值可能不匹配索引,我想将数值相乘。
  • 您的 for 循环根本不使用 i 作为索引。它将值从列表中拉出。如果您的列表是[True, 17, "foo"],那么i 在第一次迭代时将是True(解释为1),在第二次迭代时是17——再次出现超出范围的错误。如果您进行第三次迭代,您会因为尝试将字符串用作列表索引而收到类型错误。
  • 请尝试product *= i 更改。请注意,它使用索引;它使用值,而不考虑索引。
猜你喜欢
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
  • 2012-10-20
  • 1970-01-01
  • 1970-01-01
  • 2019-07-10
  • 2019-11-10
  • 1970-01-01
相关资源
最近更新 更多