Python 中的管道字符

发布于 2024-11-06 23:29:55 字数 176 浏览 2 评论 0 原文

我看到函数调用中使用了“管道”字符 (|):

res = c1.create(go, come, swim, "", startTime, endTime, "OK", ax|bx)

ax|bx 中管道的含义是什么?

I see a "pipe" character (|) used in a function call:

res = c1.create(go, come, swim, "", startTime, endTime, "OK", ax|bx)

What is the meaning of the pipe in ax|bx?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

久夏青 2024-11-13 23:29:55

这也是并集运算符,

set([1,2]) | set([2,3])

这将导致 set([1, 2, 3])

This is also the union set operator

set([1,2]) | set([2,3])

This will result in set([1, 2, 3])

可爱咩 2024-11-13 23:29:55

它是整数的按位或。例如,如果 axbx 之一或两者为 1,则计算结果为 1,否则为 <代码>0。它也适用于其他整数,例如 15 | 128 = 143,即00001111 |二进制形式为 10000000 = 10001111

It is a bitwise OR of integers. For example, if one or both of ax or bx are 1, this evaluates to 1, otherwise to 0. It also works on other integers, for example 15 | 128 = 143, i.e. 00001111 | 10000000 = 10001111 in binary.

征棹 2024-11-13 23:29:55

Python 3.9 - PEP 584 - 将联合运算符添加到字典 的标题为的部分中规范,对运算符进行了解释。
管道被增强以合并(联合)字典。

>>> d = {'spam': 1, 'eggs': 2, 'cheese': 3}
>>> e = {'cheese': 4, 'nut': 5}
>>> d | e
{'spam': 1, 'eggs': 2, 'cheese': 4, 'nut': 5} # comment 1
>>> e | d
{'cheese': 3, 'nut': 5, 'spam': 1, 'eggs': 2} # comment 2

注释 1 如果一个键同时出现在两个操作数中,则最后看到的值(即来自右侧操作数的值)获胜 --> 'cheese': 4 而不是 'cheese': 3

comment 2 奶酪出现两次,选择第二个值,因此 d[cheese]=3

In Python 3.9 - PEP 584 - Add Union Operators To dict in the section titled Specification, the operator is explained.
The pipe was enhanced to merge (union) dictionaries.

>>> d = {'spam': 1, 'eggs': 2, 'cheese': 3}
>>> e = {'cheese': 4, 'nut': 5}
>>> d | e
{'spam': 1, 'eggs': 2, 'cheese': 4, 'nut': 5} # comment 1
>>> e | d
{'cheese': 3, 'nut': 5, 'spam': 1, 'eggs': 2} # comment 2

comment 1 If a key appears in both operands, the last-seen value (i.e. that from the right-hand operand) wins --> 'cheese': 4 instead of 'cheese': 3

comment 2 cheese appears twice, the second value is selected so d[cheese]=3

焚却相思 2024-11-13 23:29:55

是的,以上所有答案都是正确的。

尽管您可以找到“|”的更多奇特用例,但如果它是类使用的重载运算符,例如

https://github.com/twitter/pycascading/wiki#pycascading

input = flow.source(Hfs(TextLine(), 'input_file.txt'))
output = flow.sink(Hfs(TextDelimited(), 'output_folder'))

input | map_replace(split_words, 'word') | group_by('word', native.count()) | output

在此特定用例中管道“|”可以更好地将运算符视为 Unix 管道运算符。但我同意,按位运算符和并集运算符是“|”更常见的用例在Python中。

Yep, all answers above are correct.

Although you could find more exotic use cases for "|", if it is an overloaded operator used by a class, for example,

https://github.com/twitter/pycascading/wiki#pycascading

input = flow.source(Hfs(TextLine(), 'input_file.txt'))
output = flow.sink(Hfs(TextDelimited(), 'output_folder'))

input | map_replace(split_words, 'word') | group_by('word', native.count()) | output

In this specific use case pipe "|" operator can be better thought as a unix pipe operator. But I agree, bit-wise operator and union set operator are much more common use cases for "|" in Python.

别在捏我脸啦 2024-11-13 23:29:55

总结与扩展以前的答案:

| 运算符最初的作用是 按位或。这是按位运算教程

f'{0b1100 | 0b1010 :04b}' == '1110'

另一方面,Python 运算符可以通过重载其等效的运算符函数来重载。特别是,可以通过实现函数 __or__(和 __ror__。任何 Python 库,无论是标准库还是用户库,都可以重载任何运算符(例如,存档的 PyCascading )。

Python 内置类型,例如 set dict 重载 < code>| 分别定义联合和合并。特别是,Python 3.9PEP 584,将重载的|和其他运算符引入到dict和其他标准库类型。

# sets; | does union of sets
#  the order does not matter, i.e., the operation is commutative
{1, 2} | {2, 3} == {1, 2, 3}

{2, 3} | {1, 2} == {1, 2, 3}


# dicts; | does "merging" of dicts
#   the order does matter, i.e., the operation is NOT commutative
{'a': 1, 'b': 2} | {'b': 99, 'c': 3} == {'a': 1, 'b': 99, 'c': 3}

{'b': 99, 'c': 3} | {'a': 1, 'b': 2} == {'a': 1, 'b': 2, 'c': 3}

同样,types.UnionType< /strong>随 Python 3.10 引入,还重载了二元或运算符|,在本例中表示 types 用于类型注释/提示,例如,typing.Union[int, str] == int | str。

最近流行的 | 运算符的重载和使用位于 Python LangChain链/管道操作。这是 LangChain 如何重载算子的具体代码

# LangChain chained sequence of components
chain = prompt | model | output_parser

Summarizing & extending previous answers:

The | operator originally does bitwise OR. Here is a tutorial on bitwise operations.

f'{0b1100 | 0b1010 :04b}' == '1110'

On the other hand, Python operators can be overloaded by overloading their equivalent operator functions. In particular, | can be overloaded by implementing the function __or__ (and __ror__). Any Python library, standard or userbase, can overload any operator (e.g., archived PyCascading).

The Python built-in types such as set and dict overload | to define union and merge, respectively. In particular, Python 3.9, PEP 584, brought the overloaded | and other operators to dict and other standard library types.

# sets; | does union of sets
#  the order does not matter, i.e., the operation is commutative
{1, 2} | {2, 3} == {1, 2, 3}

{2, 3} | {1, 2} == {1, 2, 3}


# dicts; | does "merging" of dicts
#   the order does matter, i.e., the operation is NOT commutative
{'a': 1, 'b': 2} | {'b': 99, 'c': 3} == {'a': 1, 'b': 99, 'c': 3}

{'b': 99, 'c': 3} | {'a': 1, 'b': 2} == {'a': 1, 'b': 2, 'c': 3}

Likewise, the types.UnionType, introduced with Python 3.10, also overloads the binary-or operator |, in this case to signify a union of types for type annotations/hints, e.g., typing.Union[int, str] == int | str.

A recent, popular overloading and usage of the | operator is in the Python LangChain library to chain/pipe operations. This is the exact code for how LangChain overloads the operator.

# LangChain chained sequence of components
chain = prompt | model | output_parser
最单纯的乌龟 2024-11-13 23:29:55

它是按位或。

Python 中所有运算符的文档可以在 Python 文档的 索引 - 符号 页面中找到。

It is a bitwise-or.

The documentation for all operators in Python can be found in the Index - Symbols page of the Python documentation.

若无相欠,怎会相见 2024-11-13 23:29:55

不是专门在函数调用中,而是关于 OP 标题,现在人们可能还会在键入注释中列出“”功能的管道运算符!

请参阅: https://docs.python.org/3/library/ Typing.html#typing.Union

例如:

def get_string_length(string: str | None = None) -> int:
    if string is None:
        string = 'muppets'
    return len(string)

Not specifically in function call but regarding OPs headline one might nowadays also list the pipe operator for "or" functionality in typing annotations!

See: https://docs.python.org/3/library/typing.html#typing.Union

For example:

def get_string_length(string: str | None = None) -> int:
    if string is None:
        string = 'muppets'
    return len(string)
颜漓半夏 2024-11-13 23:29:55

从 python 3.10 开始,您还可以使用管道运算符 (|) 来匹配匹配语句中的多种情况(结构模式匹配),

例如:

def http_error(status):
    match status:
        case 500:
            return "Server error"
        case 401 | 403 | 404:
            return "Not allowed"
        case _:
            return "Something's wrong with the internet"

https://docs.python.org/3/whatsnew/3.10.html#pep-634-structural-pattern-matching

Since python 3.10 you can also use the pipe operator (|) to match several cases inside the match statement (Structural Pattern Matching)

Such as in:

def http_error(status):
    match status:
        case 500:
            return "Server error"
        case 401 | 403 | 404:
            return "Not allowed"
        case _:
            return "Something's wrong with the internet"

https://docs.python.org/3/whatsnew/3.10.html#pep-634-structural-pattern-matching

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文