我是python的初学者,正在编写一个程序来计算素数直到给定N。这是我的代码。我看到的是,我调用numbers
的列表在每次迭代后通过 for 循环进行了更改。但是,我看到我正在迭代的列表仍然包含对旧值的引用,而这个列表是用 for 循环更改的。请看下面的输出。
def getprimes(n):
numbers = [ i for i in range (2,n+1)]
primes=[]
print "numbers in the beginning",numbers
for i in numbers:
print i
primes.append(i)
print "primes",primes
print "numbers",numbers
numbers=[k for k in numbers if (k%i!=0)]
print "numbers at end",numbers
return primes
print getprimes(10)
我的输出如下:
numbers in the beginning [2, 3, 4, 5, 6, 7, 8, 9, 10]
2
primes [2]
numbers [2, 3, 4, 5, 6, 7, 8, 9, 10]
3
primes [2, 3]
numbers [3, 5, 7, 9]
4
primes [2, 3, 4]
numbers [5, 7]
5
primes [2, 3, 4, 5]
numbers [5, 7]
6
primes [2, 3, 4, 5, 6]
numbers [7]
7
primes [2, 3, 4, 5, 6, 7]
numbers [7]
8
primes [2, 3, 4, 5, 6, 7, 8]
numbers []
9
primes [2, 3, 4, 5, 6, 7, 8, 9]
numbers []
10
primes [2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers []
numbers at end []
[2, 3, 4, 5, 6, 7, 8, 9, 10]
欢迎任何建议和意见!谢谢