- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个这样的当前实现:
class Infix(object):
def __init__(self, func):
self.func = func
def __or__(self, other):
return self.func(other)
def __ror__(self, other):
return Infix(partial(self.func, other))
def __call__(self, v1, v2):
return self.func(v1, v2)
@Infix
def Map(data, func):
return list(map(func,data))
这很好,它按预期工作,但我还想扩展此实现以允许仅左侧解决方案。如果有人可以展示解决方案和解释,那就太好了。
这是我想做的一个例子...
valLabels['annotations'] \
|Map| (lambda x: x['category_id']) \
|Unique|
Unique 定义如下...
@Infix
def Unique(data):
return set(data)
谢谢!
最佳答案
如果你不介意删除最后的|
,你可以这样做
class InfixR(object):
def __init__(self, func):
self.func = func
def __ror__(self, other):
return self.func(other)
def __call__(self, v1):
return self.func(v1)
@InfixR
def Unique(data):
return set(data)
那么你的表情会是这样
valLabels['annotations'] \
|Map| (lambda x: x['category_id']) \
|Unique
您原来的 Infix
类(技术上)滥用了 bitwise or
运算符:|Map|
没什么特别的,它只是 值(value) | map | my_lambda
,列表、对象和 lambda 的“按位或”,删除了几个空格,并插入了一些换行符(使用 \
来防止解释器尝试分别处理每一行)。
在自定义类中,您可以使用__double_underscore__
方法实现许多常用运算符,在按位或的情况下,它们是__or__
和__ror__
。
当 python 解释器遇到 |
运算符时,它首先查看右边的对象,看它是否有 __or__
方法。然后调用 left.__or__(right)
。如果未定义或返回 NotImplemented
,它会查看右侧的对象,对于 __ror__
(反向或),并调用 right.__ror__(left)
。
另一部分是装饰器符号。
当你说
@Infix
def Unique(data):
return set(data)
解释器将其扩展为
def Unique(data):
return set(data)
Unique = Infix(Unique)
所以你得到一个 Infix
实例,它有 __or__
和 __ror__
方法,以及一个 __call__
方法。您可能会猜到,当您调用 my_oby()
时,将调用 my_obj.__call__()
。
关于python - Python 中的函数式中缀实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38962846/
前缀表达式 前缀表达式又称波兰式,前缀表达式的运算符位于操作数之前。 例如: ( 3 + 4 ) × 5 − 6 (3+4)×5-6(3+4)×5−6 对应的前缀表达式就是 - × + 3 4 5 6
众所周知: ((.).(.)) :: (b -> c) -> (a -> a1 -> b) -> a -> a1 -> c 我可以像这样使用这个复合运算符前缀样式: ((.).(.)) f g 但看起
换句话说,我可以使用什么语法(如果有)来代替 XXX在过滤器的以下实现中: filter' :: (a -> Bool) -> [a] -> [a] filter' _ [] = [] fil
在 R 中,每当两个包定义相同的函数时,很容易指定使用哪个包 pkg::foo .但是当冲突的函数是中缀运算符时你怎么办,即使用 %% 定义? 例如,ggplot2和 crayon定义 %+% .有没
关于代码的简短介绍:我必须创建一个类来计算前缀、后缀或中缀表达式。它必须判断是否是pre/post/infix并将其转换为后缀,例如从'/x7'转换的代码中的prefixTOpostfix()(其他已
前缀表达式(波兰表达式) 前缀表达式又称波兰表达式,前缀表达式的运算符位于操作符之前,如(3+4)*5-6对应的前缀表达式就是- * + 3 4 5 6 前缀表达式的计算机求
我需要使用 VBA 对数学表达式进行标记。我有一个可行的解决方案,但正在寻找一种更有效的方法(可能是 RegExp)。 我当前的解决方案: Function TokeniseTheString(str
我正在编写一个包含如下函数的包: "%IN%" 0 当我 Build & Reload 包时(我使用 RStudio),这个函数不可用,与包中定义的所有其他函数相反。 我如何使它工作? 最佳答案 解
我一直在用 Java 开发表达式求值器,出于沮丧,我也来这里询问。到目前为止,我至少重写了 15 次,但每次都无济于事。 基本上我需要在前缀、中缀或后缀中获取一个字符串并将其计算为整数。该表达式可以使
C++ 中的运算符通常被认为是函数/方法的替代语法,尤其是在重载的上下文中。如果是这样,下面的两个表达式应该是同义词: std::cout & __out, char __c) operator& _
我是一名优秀的程序员,十分优秀!