Python IndexError: list index out of range when using a list as an iterable

僤鯓⒐⒋嵵緔 提交于 2019-12-02 08:07:08

问题


Here is the code:

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)

Running this code gives this error:

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

Which really doesn't make any sense to me as the i in the for loop is a given index in the list and shouldn't exceed the bounds of that list.


回答1:


You've confused the list index with the list contents. for i in n means that i will take on the values of n in sequence: 2, 3, 5, 7, 11, ...

From Python's point of view ... n has 42 elements. As soon as you get to accessing n[i] when i is 43, you crash.

Try this:

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

Do note that this fails in your MCVE, because you don't have enough primes to get to sqrt(primeproduct).




回答2:


for i in n iterates over the values not the indicies. If you want the indicies there are a couple ways you could do it, one being for i, v in enumerate(n) and then you can use v instead of n[i].




回答3:


Which really doesn't make any sense to me as the i in the for loop is a given index in the list and shouldn't exceed the bounds of that list.

Not quite. i is an item in your list, not an index.

for i in n gives you the items in n. Not the index. So doing n[i] is a bit nonsensical (you're using the items as indices). A quick fix is to use for i in range(len(n)) if you want a c-style index.

More pythonic would be:

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


来源:https://stackoverflow.com/questions/53528484/python-indexerror-list-index-out-of-range-when-using-a-list-as-an-iterable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!