pipe|Python 中的运算符
通常称为“pipe”,是Python中的一个运算符,可以简洁地定义不同的计算。让我们来看看其中的一些:|
按位或的经典用法是按位执行,或者它在许多语言中都是这样做的,
例如Java,C,C++和JavaScript等等。
同样,当在数字之间执行时,它也在 Python 中用于此目的。
例如:|
a = 4 # in binary 0100 = 0*2^3 + 1*2^2 + 0*2^1 + 0*2^0 = 4
b = 8 # in binary 1000 = 1*2^3 + 0*2^2 + 0*2^1 + 0*2^0 = 8
# bitwise or:
# 0100
# 1000
# => 1100 = 12
print(a | b)
# => 12
同样用于按位和 &
合并词典
从 Python 3.9 开始,运算符可用于合并字典:|
a = { "a": 5, "b": 6 }
b = { "c": 7 }
print(a | b)
# => {'a': 5, 'b': 6, 'c': 7}
请注意,如果字典共享键,则将保留操作中最后一个字典中的值:
a = { "a": 5, "b": 6 }
b = { "a": 7 }
print(a | b)
# => {'a': 7, 'b': 6}
您还可以链接操作以合并多个词典:
a = { "a": 5, "b": 6 }
b = { "a": 7 }
c = { "a": 8, "c": 10 }
print(a | b | c)
# => {'a': 8, 'b': 6, 'c': 10}
集合的联合
Python 中的 A 是一个没有重复项的无序元素集合。它提供了快速的成员资格检查和许多有用的操作,例如集合的联合。集合的并集是所有集合的组合元素(没有重复),这里可以使用运算符:set|
a = set([1, 2, 3])
b = set([2, 3, 4])
# union:
print(a | b)
# or equivalently
print(a.union(b))
它也可以链接:
a = set([1, 2, 3])
b = set([2, 3, 4])
c = set([3, 4, 5])
print(a | b | c)
# => {1, 2, 3, 4, 5}
元素布尔值或 NumPy 和Pandas
在 NumPy 和 Pandas 中,具有执行逐元素布尔或的重要目的。我在这里强调重要,因为它可以实现相当大的加速,而不是在熊猫中使用。
让我们用一个例子来说明这一点
|.apply()
from time import time
import numpy as np
import pandas as pd
a = pd.Series(np.arange(1000000))
# using .apply()
start_time = time()
b = a.apply(lambda x: x 700000)
print(time() - start_time)
# => 0.1980600357055664
start_time = time()
b = (a 700000)
print(time() - start_time)
# => 0.0020973682403564453
运行这个时,元素方面或快了 94 倍!同样,您可以使用 执行逐个元素和。当速度很重要时,这些操作员是必不可少的。
&类型提示中的联合
为允许具有多种类型的变量指定类型提示时,可以使用该类型:Union
from typing import Union
def some_method(
# a can be of type str or int
a: Union[str, int]
):
...
但你也可以从 Python 3.10 使用,并编写:|
def some_method(
# a can be of type str or int
a: str | int
):
...
您自己的操作 最后,您可以通过执行运算符重载来定义自己对自己的类的用法。
为此,您只需在类中定义一个名为 .让我们创建一个有趣的示例,其中方法被链接在一起:|__or__
class Callback:
def __init__(self, func):
self.func = func
# implementing this method will enable
# the | operator for this class:
# a | b
# where a will be self, and b will be
# the first argument in __or__
def __or__(self, other):
# chain the methods
def combined_func(input):
# self(...) can be used since
# __call__ is defined below
tmp = self(input)
return other(tmp)
return Callback(combined_func)
def __call__(self, input):
return self.func(input)
通过重载 -运算符,现在可以链接回调以生成新的回调:__or__
method = (
Callback(lambda x: x + 1) |
Callback(lambda x: x * 2) |
Callback(lambda x: x ** 2)
)
print(method(3)) # ((3+1) * 2) ** 2 = 64
# => 64
print(method(4)) # ((4+1) * 2) ** 2 = 100
# => 100
……省略号
省略号或省略号是Python中的一个常量,用于各种情况,通常表示与普通文本相同的含义,即“等等”或“某些东西应该在这里”。
请注意,键入 和 是等效的:……Ellipsis
assert Ellipsis == ...
让我们来看看它的一些用途。
在数字派中 在 NumPy 中使用多个维度时,省略号可用于表示“其余维度”,即:
import numpy as np
tensor = np.random.uniform(size=(10, 10, 10, 10, 10))
print(tensor[0, ...].shape)
# corresponds to tensor[0, :, :, :, :]
# => (10, 10, 10, 10)
print(tensor[0, 0, ...].shape)
# corresponds to tensor[0, 0, :, :, :]
# => (10, 10, 10)
print(tensor[0, 0, ..., 0].shape)
# corresponds to tensor[0, 0, :, :, 0]
# => (10, 10)
print(tensor[0, 0, ..., 0, 0].shape)
# corresponds to tensor[0, 0, :, 0, 0]
# => (10,)
有关更多NumPy技巧,请查看这篇文章。
作为占位符
使用 指示函数不执行任何操作或应稍后完成的替代方法是使用 :passEllipsis
def my_method():
...
你也可以把它用在类上:
class MyClass:
...
如果你像我一样,在写文本时为你打算以后填写的内容写”…”,这种方法应该很自然。
类型化
在不同的情况下,Ellipsis 可以在 Python 的类型提示中使用。
元组
当为一个元组添加类型提示时,你可以把它定义为固定长度或可变长度。在后一种情况下,Ellipsis进入了画面。让我们看一些例子:
from typing import Tuple
def some_method(
# ex: (1, "hello", 2)
a: Tuple[int, str, int],
# ex: ()
b: Tuple[()],
# variable length!
# ex: (1, 2, 3, 4) or (1, 2)
c: Tuple[int, ...],
): ...
变量的类型提示说,元组可以包含任何数量的ints。那么你如何定义一个任何类型的变长元组呢?有两个选择:
from typing import Tuple, Any
def some_other_method(
# option 1
a: Tuple[Any, ...],
# option 2 (equivalent to option 1)
b: Tuple
): ...
Callable
类型的对象是可以调用的东西,例如方法。在理解此处省略号的作用之前,让我们先了解一下类型提示通常是如何定义的:CallableCallable
from typing import Callable
Callable[[TypeOfFirstArg, TypeOfSecondArg, and so on...], ReturnType]
了解一下类型提示通常是如何定义的:
CallableCallable
from typing import Callable
def some_method(
# takes zero arguments, returns nothing/None
# ex: a()
a: Callable[[], None],
# takes two arguments, an int and a string, returns an int
# ex: b(1, "hello")
b: Callable[[int, str], int],
):
a()
b(1, "hello")
但是,如果应该能够接受任何类型的任意数量的参数呢?这就是省略号的用武之地。只需按如下方式定义它:Callable
def some_other_method(
# takes any number of arguments of any type, returns an int
# ex: c(1, 2, 3, 4) or c()
c: Callable[..., int],
):
c()
c(1,2,3)
另请注意,只需指定:
d: Callable意味 着:
d: Callable[..., Any]
即接受任意数量的参数并返回任何内容的方法。顺便说一下,从 Python 3.10 开始重载运算符,省略号也有了自己的类型:.types.EllipsisType
您自己的函数和类
就像 一样,the 是一个单例,这意味着整个程序中只有一个对象的实例,任何对 的引用都将指向内存中的同一对象。
例如:Field
class Model(BaseModel):
# a list of strings that is required and needs to have at least 5 items
a_required_attr: List[str] = Field(..., min_items=5)
因此重载运算符,每当省略号在语义上有意义和/或您想要另一个单例时,它就可以在您的类或方法中使用。
Pydantic是一个流行的数据验证库,省略号可以用作所谓的 -function 的第一个参数,以指定属性是必需的。
限时特惠:本站每日持续更新海量设计资源,一年会员只需29.9元,全站资源免费下载
站长微信:ziyuanshu688