迭代器
迭代器是最近才加入Python中的,在数学应用中特别有用。下面是几个例子,更多内容请参见PyT。我们生成一个在不超过$10000000$的非负整数的平方数上的迭代器。
sage: v = (n^2 for n in xrange(10000000)) # py2sage: v = (n^2 for n in range(10000000)) # py3sage: next(v)0sage: next(v)1sage: next(v)4
我们新建一个在形如$4p+1$($p$为素数) 的素数上的迭代器, 并观察前面几个。
sage: w = (4*p + 1 for p in Primes() if is_prime(4*p+1))sage: w # 输出的0xb0853d6c为随机的十六进制数<generator object at 0xb0853d6c>sage: w.next()13sage: w.next()29sage: w.next()53
特定的环,如有限域和整数环上都有迭代器:
sage:[x for x in GF(7)][0, 1, 2, 3, 4, 5, 6]sage: W = ((x,y) for x in ZZ for y in ZZ)sage: W.next()(0, 0)sage: W.next()(0, 1)sage: W.next()(0, -1)
