简体   繁体   English

用Python编写迭代器

[英]Currying iterators in Python

In the following snippet I try to return a function which is returning a generator (weren't they once called iterators BTW?) with the step argument curried. 在以下代码段中,我尝试返回一个函数,该函数将返回带有生成器的生成器(它们曾经被称为迭代器BTW吗?),并带有step参数。

import math
import numpy

def aequi_ang_step(step):
    def local_it(start, d_alpha, step):
        for alpha in numpy.arange(start, start+d_alpha,(d_alpha < 0) and -step or step):
            if (alpha < 2*math.pi): yield alpha
            else: yield alpha-2*math.pi
    return lambda start, d_alpha: local_it(start, d_alpha, step)

The thing works but as I am returning from a long abstinence back to Python my question is if this is an ok and pythonic way to curry iterators in Python. 事情是可行的,但是当我从长时间的禁欲中恢复到Python时,我的问题是这是否是在Python中使用迭代器来实现迭代器的一种好方法。

This is not exactly how I would approach the problem here. 这不完全是我在这里解决问题的方式。 In particular, returning a lambda is discouraged. 特别是不鼓励返回lambda Consider instead 考虑代替

import math
import numpy

def aequi_ang_step(step):
    def local_it(start, d_alpha):
        for alpha in numpy.arange(start, start+d_alpha,(d_alpha < 0) and -step or step):
            if (alpha < 2*math.pi): yield alpha
            else: yield alpha-2*math.pi
    return local_it

Now what you return is a closure which includes a definition for step . 现在,您返回的是一个闭包,其中包含step的定义。

I think a more pythonic approach in general for currying, is functools.partial 我认为一般来说,更复杂的pythonic方法是functools.partial

from functools import partial
import math
import numpy

step = 0.1

def aequi_ang(start, d_alpha, step):
    for alpha in numpy.arange(start, start+d_alpha,(d_alpha < 0) and -step or step):
        if (alpha < 2*math.pi): yield alpha
        else: yield alpha-2*math.pi

aequi_ang_step = partial(aequi_ang, step=step)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM