operator python参数

Iza*_*ela 6 python parameters function

在Python中,如何将运算符+<作为参数传递给期望比较函数作为参数的函数?

def compare (a,b,f):
    return f(a,b)
Run Code Online (Sandbox Code Playgroud)

我已经阅读了类似的功能__gt__(),__lt__()但我仍然无法使用它们.

Mic*_*rer 11

运营商模块是你在找什么.在那里,您可以找到与通常操作员相对应的功能.

例如

operator.lt
operator.le
Run Code Online (Sandbox Code Playgroud)


Art*_*nka 5

为此目的使用操作员模块

import operator
def compare(a,b,func):

    mappings = {'>': operator.lt, '>=': operator.le,
                '==': operator.eq} # and etc. 
    return mappingsp[func](a,b)

compare(3,4,'>')
Run Code Online (Sandbox Code Playgroud)

  • 为什么`lambda`?你不只是想要`{'>':operator.lt,'> =':operator.le,...}` (2认同)