【问题标题】:Python IndexError: list index out of range when using a list as an iterablePython IndexError:将列表用作可迭代对象时,列表索引超出范围
【发布时间】:2019-04-30 21:27:56
【问题描述】:

代码如下:

import math as m
primeproduct = 5397346292805549782720214077673687806275517530364350655459511599582614290
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181]

def pseudoroot(n):
print(n)
for i in n:
    if n[i] > m.sqrt(primeproduct):
        return n[i-1] #greatest divisor below the root


psrprime = pseudoroot(primes)

运行此代码会出现此错误:

Traceback (most recent call last):
  File "so.py", line 11, in <module>
    print(pseudoroot(primes))
  File "so.py", line 7, in pseudoroot
    if n[i] > m.sqrt(primeproduct):
IndexError: list index out of range

这对我来说真的没有任何意义,因为 for 循环中的 i 是列表中的给定索引,不应超出该列表的范围。

【问题讨论】:

  • primeprod 定义在哪里?
  • n[i] 是索引,而不是值。例如,当i 为47 时,代码试图在索引47 处查找primeprod 中的值

标签: python index-error


【解决方案1】:

这对我来说真的没有任何意义,因为 for 循环中的 i 是 列表中的给定索引,不应超过该索引的范围 列表。

不完全是。 i 是列表中的项目,不是索引。

for i in n 为您提供n 中的项目。不是索引。所以这样做n[i] 有点荒谬(您使用 items 作为索引)。如果你想要一个 c 风格的索引,一个快速的解决方法是使用for i in range(len(n))。

更多的pythonic是:

for before_prime, current_prime in zip(n, n[1:]):
    if current_prime > m.sqrt(primeprod):
        return before_prime #greatest divisor below the root

【讨论】:

    【解决方案2】:

    您将列表 index 与列表 contents 混淆了。 for i in n 表示i 将依次采用n 的值:2, 3, 5, 7, 11, ...

    从 Python 的角度来看...n 有 42 个元素。当我 43 岁时,一旦你访问 n[i],你就会崩溃。

    试试这个:

    def pseudoroot(n):
        for i, p in enumerate(n):
            if p > m.sqrt(primeproduct):
                return n[i-1] #greatest divisor below the root
    

    请注意,这在您的 MCVE 中失败,因为您没有足够的素数来访问 sqrt(primeproduct)。

    【讨论】:

      【解决方案3】:

      for i in n 迭代 值 而不是索引。如果你想要这些指标,有几种方法可以做到,一种是for i, v in enumerate(n),然后你可以使用v 而不是n[i]。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-25
        • 2017-04-05
        • 2012-07-15
        • 2013-06-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多