带有range()的循环的python

时间:2015-09-26 14:44:58

标签: python loops for-loop range

由于某种原因,我总是试图用我的头围绕着范围循环。

代码:

# 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 - >真假是等于真。

1 个答案:

答案 0 :(得分:3)

您错过了nums每次迭代都会被过滤的事实。因此,在第一次迭代中,x%2不为0的所有数字(包括4)都被过滤掉。

如果您在循环中添加了额外的print nums,则在过滤器之后,您会更清楚地看到这一点。