如何在Python中打印带索引的素数的真/假列表?

如何在Python中打印带索引的素数的真/假列表?,python,list,Python,List,我的函数为素数输出True,为非素数输出False def is_prime(x): if x < 2: return False else: for n in range(2,x-1): if x % n == 0: return False return True 实现这一点最简单的方法是什么?因为,你基本上是在返回埃拉托斯坦筛中的旗帜。也许您应该

我的函数为素数输出True,为非素数输出False

   def is_prime(x):
      if x < 2:
        return False
      else:
        for n in range(2,x-1):
          if x % n == 0:
            return False
        return True   
    

实现这一点最简单的方法是什么?

因为,你基本上是在返回埃拉托斯坦筛中的旗帜。也许您应该直接使用该方法:

def is_prime(x):
  if x < 2:
    return False
  else:
    for n in range(2,x-1):
      if x % n == 0:
        return False
    return True   
    

def num_range(x):
    for i in range(x):
        print([i],[is_prime(i)])

num_range(5) # send how many numbers you want to print
def sieve(x):
    result = [False]*2+[True]*(x-1)
    p,i = 2,1                                            # 2,3,5,7,...
    while p*p<=x:                                        # only up to √x
        if result[p]:                                    # found a prime
            result[p*p::p] = [False]*len(result[p*p::p]) # flag multiples
        p,i = p+i,2                                      # next candidate                            
    return result

您是在问如何在for循环中调用函数,还是您的任务中有一个特定的部分需要处理?如何准确定义
primelist
?您可以始终使用
枚举
将iterable的每个元素与递增整数配对。@Sayse我编辑了这个问题。我的工作就是输出正确/错误语句的索引。
[0] [False]                                                                                                                                   
[1] [False]                                                                                                                                   
[2] [True]                                                                                                                                    
[3] [True]                                                                                                                                    
[4] [False]
def sieve(x):
    result = [False]*2+[True]*(x-1)
    p,i = 2,1                                            # 2,3,5,7,...
    while p*p<=x:                                        # only up to √x
        if result[p]:                                    # found a prime
            result[p*p::p] = [False]*len(result[p*p::p]) # flag multiples
        p,i = p+i,2                                      # next candidate                            
    return result
x = 10
for i,isPrime in enumerate(sieve(x)):
    print([i],[isPrime])

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