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

时间:2014-01-07 10:08:48

标签: python loops iterator

我是Python的新手并处理一个素数生成器。我想使用的算法是Sieve of Atkin

此时,我正在尝试按照算法的伪代码作为我的练习。但是,我遇到了一个问题,我找不到任何关于它的参考。 (也许我不擅长搜索......)。在伪代码中,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()

2 个答案:

答案 0 :(得分:4)

for (x, y) in [1, √limit] × [1, √limit]应转换为产品:

for x in itx:
    for y in ity:

或使用itertools.product()

from itertools import product

for x, y in product(itx, ity):

请注意,需要在迭代器上调用.next()!删除itx.next()ity.next()行,除非您表示以跳过生成的值。 for构造为您推进了迭代器。

答案 1 :(得分:3)

而不是zip(itx, ity),您需要使用itertools.product(itx, ity)

zip并行迭代两个迭代器(操作称为convolution),产生匹配项对,并在最短迭代器耗尽时结束迭代。 itertools.product遍历两个迭代器中的Cartesian product,从一个集合中生成所有项目组合。后者是×运算符所指的。

正如Martijn Pieters指出的那样,在迭代器上手动调用.next()是不正确的,因为for自己推进它们,并且自己动手,最终只处理迭代的每一秒项。此外,iter(range(...))是不必要的 - 只需在Python 3中使用xrange(或range)。

相关问题