1

如果我有一个包含 20 个数字的输入队列,我怎样才能得到所有数字的总和?到目前为止,这是我想出的:

import bonobo as bb
from bonobo.config import Configurable, ContextProcessor
from bonobo.util import ValueHolder

def extract_nums():
    yield 1
    yield 2
    yield 3

class TransformNumber(Configurable):
    @ContextProcessor
    def total(self, context):
        yield ValueHolder({'extract':0,'transform':0})

    def __call__(self, total, num, **kwargs):
        total['extract']+=num
        transform_num = num * 10
        total['transform']+=transform_num
        if num==3: # Final number
            print("TOTALS:",total.get())
        yield transform_num

graph = bb.Graph()
graph.add_chain(
    extract_nums,
    TransformNumber(),
    bb.PrettyPrinter()
)

可以这样做还是有更好的方法?

4

1 回答 1

2

在 Bonobo ETL 节点中保持本地状态有不同的可用选项。

可以像您那样做(尽管我认为这很难阅读),我倾向于使用我认为更具可读性的闭包(但我同意,这是值得商榷的):

import bonobo


def CumSum():
    total = 0

    def cum_sum(x):
        nonlocal total
        total += x
        yield x, total

    return cum_sum


def get_graph(**options):
    graph = bonobo.Graph()
    graph.get_cursor() >> range(100) >> CumSum() >> print

    return graph


# The __main__ block actually execute the graph.
if __name__ == "__main__":
    parser = bonobo.get_argument_parser()
    with bonobo.parse_args(parser) as options:
        bonobo.run(get_graph(**options))

bonobo 源代码中提供了一些示例,请查看https://github.com/python-bonobo/bonobo/blob/develop/bonobo/nodes/basics.py(并且有以不同风格编写的示例)。

请注意,我在这里使用 Bonobo 0.7(传入)语法来构建图形,但是通过 add_chain 调用替换“>>”运算符,可以在当前稳定版本(0.6)中使用相同的东西。

于 2018-11-09T06:37:35.943 回答