2015-09-26 290 views
0

由於某種原因,我試圖包裹我的頭圍繞循環與範圍。蟒蛇for循環與範圍()

代碼:

# inefficient way to compute primes with "filter" 
nums = range(2, 100) 
for i in range(2, 8): 
    """Sieve of Eratosthenes: 
     Leave the element in the list if it is equal to "i", 
     or if it leaves a non-zero remainder when divided by "i". 
     """ 
    # (x % i returns either zero or non-zero, 0 -> False, non-0 -> True) 
    nums = filter(lambda x: x == i or x % i != 0, nums) 

print nums 

生產這種輸出(即素數多達100個):

[ 
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 
] 

這是第二個問題,關於這一點,我在這裏問,我不能爲生命我弄清楚這是如何工作的。有人可以一步一步地解釋(最好能夠使其可視化),這裏究竟發生了什麼。例如,爲什麼4不會打印爲素數?由於x == i(即4 == 4)或x%i - > False True等於True。

+1

您可能想嘗試類似http://www.pythontutor.com/visualize.html – jonrsharpe

回答

3

您錯過了每次迭代都會過濾nums的事實。因此,在第一次迭代中,x%2不是0的所有數字(包括4)都被濾除。

如果您在循環內部添加了一個額外的print nums,在過濾器之後,您會更清楚地看到它。