什么是管道和>>在Python中?

2024-09-28 05:40:48 发布

您现在位置:Python中文网/ 问答频道 /正文

最近我在学习ApacheBeam,发现了一些类似这样的python代码:

lines = p | 'read' >> ReadFromText(known_args.input)

  # Count the occurrences of each word.
  def count_ones(word_ones):
    (word, ones) = word_ones
    return (word, sum(ones))

  counts = (lines
            | 'split' >> (beam.ParDo(WordExtractingDoFn())
                          .with_output_types(unicode))
            | 'pair_with_one' >> beam.Map(lambda x: (x, 1))
            | 'group' >> beam.GroupByKey()
            | 'count' >> beam.Map(count_ones))

发件人:https://github.com/apache/beam/blob/master/sdks/python/apache_beam/examples/wordcount.py#L92

python中|>>的语法和用法是什么?你知道吗


Tags: 代码mapreadinputapachecountwithones
1条回答
网友
1楼 · 发布于 2024-09-28 05:40:48

默认情况下,|表示逻辑或逐位运算符,>>表示右移位,但幸运的是,您可以在Python中重载运算符。因此,为了拥有|>>,的自定义定义,您只需在类^{}^{}中重载以下两个dunder(magic)方法:

class A():
    def __or__(self):
        pass
    def __rshift__(self):
        pass

我建议您阅读更多关于Python Data Model的内容。你知道吗

现在查看Beam Python SDK,__or__PTransform类中重载:

  def __or__(self, right):
    """Used to compose PTransforms, e.g., ptransform1 | ptransform2."""
    if isinstance(right, PTransform):
      return _ChainedPTransform(self, right)
    return NotImplemented

相关问题 更多 >

    热门问题