具有2个迭代器和2个范围的for循环

PCH*_*CHC 2 python iterator loops

我是Python的新手,并且正在处理prime生成器。我要使用的算法是Atkin的Sieve

目前,我正在尝试按照算法的伪代码进行练习。但是,我遇到了一个问题,因此找不到任何参考。(也许我不擅长搜索...)。在伪代码中,for (x, y) in [1, ?limit] × [1, ?limit]:...让我感到困惑。我知道这是什么意思,但不知道如何将此代码转换为Python代码。

抱歉,如果我的问题不合适,谢谢您的帮助。:)

以下是我的代码的一部分。

itx = iter(range(1, int(limit**0.5)))
ity = iter(range(1, int(limit**0.5)))
for x, y in zip(itx, ity):
    n = 4*(x**2)+(y**2)
    if n <= limit and (n%12 == 1 or n%12 == 5):
        sieve[n] = not sieve[n]

    n = 3*(x**2)+(y**2)
    if n <= limit and n%12 == 7:
        sieve[n] = not sieve[n]

    n = 3*(x**2)-(y**2)
    if x > y and n <= limit and n%12 == 11:
        sieve[n] = not sieve[n]

    itx.next()
    ity.next()
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

for (x, y) in [1, ?limit] × [1, ?limit] 应该翻译成产品:

for x in itx:
    for y in ity:
Run Code Online (Sandbox Code Playgroud)

或使用itertools.product()

from itertools import product

for x, y in product(itx, ity):
Run Code Online (Sandbox Code Playgroud)

请注意,你不会需要调用.next()的迭代器!取出itx.next()ity.next()线,除非你的意思是跳过生成的值。该for构造为您推进了迭代器。