Py学习  »  Python

python“indexerror:索引8超出轴0的界限,大小为8”

DJBlom • 7 年前 • 1739 次点击  

这个问题需要我编写一个函数,它从给出两个列表的给定函数的输出中编译一个质数列表,一个是从2到任意数字的数字列表,另一个是将第一个列表中的数字与“true”或“false”值匹配的列表,具体取决于第一个列表中的数字是否为质数。

我不知道我的代码在回答问题时是否是根本错误的,或者我是否在正确的轨道上并且刚刚犯了一个错误…

任何帮助都将不胜感激。

问题:

编写一个接受单个输入n的函数(称为素数列表)。此函数必须使用素数筛选函数计算并返回仅小于或等于n+1素数的数组(或列表)。

例如,如果n=8,则此函数应返回[2,3,5,7]

给定的代码:

import numpy as np

def prime_sieve(N):
    nums = np.arange(2, N+2, 1)
    mask = []
    for n in nums:
        mask.append(True)
    for n in nums:     
        for i in np.arange(2*n-2, N, n):
            mask[i] = False
    return nums, np.array(mask)

numbers, mask = prime_sieve(8)
print(numbers)
print(mask)

[2 3 4 5 6 7 8 9]
[ True  True False  True False  True False False]

我的代码:

import numpy as np

def primes_list(N):
    numbers, mask = prime_sieve(N)
    primes = []
    for n in numbers:
        if mask[n] == "true":
            primes.append(numbers[n])
    return primes

print(primes_list(8))

但这会产生一个错误:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
 <ipython-input-60-4ea4d2f36734> in <module>
----> 2 print(primes_list(8))

<ipython-input-59-a5080837c5c8> in primes_list(N)
      6     primes = []
      7     for n in numbers:
----> 8         if mask[n] == "true":
      9             primes.append(numbers[n])
     10     return primes

IndexError: index 8 is out of bounds for axis 0 with size 8
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/30342
文章 [ 1 ]  |  最新文章 7 年前
Chris
Reply   •   1 楼
Chris    7 年前

你的 n ,用于分割列表 mask 是不适合索引的数字列表(因为它始终包含n,n+1,而最后一个索引 面具 是n-1)。

另外,第二个列表 面具 包含 Bool str ,所以你比较 mask[n] == 'true' 总是 返回 False .

考虑到以上几点, primes_list 可以是:

def primes_list(N):
    numbers, mask = prime_sieve(N)
    primes = []
    for i, n in enumerate(numbers): # <<< added enumerate 
        if mask[i]:                 # <<< removed unnecessary comparison
            primes.append(n)        # <<< append n directly
    return primes

回报:

[2, 3, 5, 7]

应该是这样的。