python for 循环与 range()

问题描述 投票:0回答:2

出于某种原因,我花了很多时间尝试用范围循环来解决问题。

代码:

# 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 --> True 或 False 等于 True。

python loops for-loop range
2个回答
3
投票

您忽略了

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

如果你在循环中添加一个额外的

print nums
,在过滤器之后,你会更清楚地看到这一点。


0
投票

您的代码利用 Eratosthenes 方法来识别 100 以内的素数。它初始化一个名为

nums
的列表,其中包含从 2 到 99 的数字。然后,它对数字 2 到 7 执行循环。在每个迭代时,使用
filter
函数和 lambda 表达式进行过滤过程。此操作消除
nums
中可被
i
当前值整除或与
i
本身相同的数字。每次迭代后,
nums
都会更新以仅保留剩余的素数。像 4 这样的数字会从最终结果中删除,因为它们在过滤过程中会被 2 整除而被识别为合数。

© www.soinside.com 2019 - 2024. All rights reserved.