python 使用 range() 进行循环
python for loop with 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 --> True of False 等于 True。
您忽略了 nums
在每次迭代中都被过滤的事实。因此,在第一次迭代中,所有 x % 2 不为 0 的数字(包括 4)都被过滤掉。
如果在循环中添加一个额外的 print nums
,在过滤器之后,您会看得更清楚。
出于某种原因,我花了很多时间尝试围绕范围循环进行思考。
代码:
# 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 of False 等于 True。
您忽略了 nums
在每次迭代中都被过滤的事实。因此,在第一次迭代中,所有 x % 2 不为 0 的数字(包括 4)都被过滤掉。
如果在循环中添加一个额外的 print nums
,在过滤器之后,您会看得更清楚。