在 Python 3.6.1 中创建素数列表并打印出列表

Creating a list of Primes and printing out the list in Python 3.6.1

我正在努力学习 Python,但我仍然很陌生。我正在尝试创建一个数字列表,从 2 到用户将输入的数字,遍历列表并从该列表中删除所有非素数,然后将其打印出来。我在计算时遇到问题,因为我不断收到错误:列表索引超出范围。我正在考虑使用 for 循环,但是变量 i 会低于变量 current 并且我需要确保 i 在通过列表时始终高于 current 。我只允许使用基本函数和循环来完成任务。

counter = 2

current = 2

n = int( input( "Please enter a number larger than 2. " ) )

while counter <= n:
    userList.append( counter )
    counter = counter + 1

print( "Printing out list " )
print( userList )

i = 1

while i <= len( userList ):
    if userList[ i ] % current == 0:
        userList.remove( userList[i] )
        i = i + 1
    else:
        current = current + 1

print( userList )

你的代码有一些错误。

1) 从大列表中删除非常 慢,因为您需要将所有内容移动到已删除的项目之后以避免列表中的项目之间出现任何间隙。最好将项目标记为已删除,然后只打印其中剩余的内容。

2) 通过使用您的算法,您需要两个 while 循环。

3) 如果你有一个包含 N 项的列表,那么列表的最后一个索引是 (N-1)。

更多 Pythonic 解决方案:

#!/usr/bin/env python3

n = int(input("Maximal number: "))
numbers = list(range(2, n+1))

i = 0
while i < len(numbers):
    if numbers[i] != None:
        j = i + 1
        while j < len(numbers):
            if numbers[j] != None:
                if numbers[j] % numbers[i] == 0:
                    numbers[j] = None
            j += 1
    i += 1

print(list(filter(lambda x: x is not None, numbers)))`