Python比较求值器替换

2024-04-25 04:07:09 发布

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

我想根据字符串的上下文替换一个比较标记。我在python3.5上做了一个PyQt5实验

例如:

line = "<"

if 1 line 2:
    print("False")

有什么简单的方法吗?我考虑使用这样的测试用例:

if line == "<":
    if 1 < 2:
        print("False")

等等,等等,但是这会变得很长,尤其是迭代的“if”语句。 例如:

if pt1 < pt1_target:
    if pt2 > pt2_target:
        etc.

或者,如果这是不可能的,是否有人有任何解决方案,以避免一个庞大的,一网打尽的“如果”语句块为每个分支?我计划在line中放一条小指令,这样line就可以替换正确的python等价物,比如"=",而不是正确的"=="

提前谢谢


Tags: 方法字符串标记falsetargetiflineetc
2条回答

可以使用字典将运算符字符串映射到operator模块中的相应函数:

import operator

ops = {'>': operator.gt,
       '<': operator.lt,
       '==': operator.eq,
       # etc...
      }

op_string = '<'
if ops[op_string](1, 2):
    print('True')
# or this...
print(ops[op_string](1, 2))

注意,这个示例打印True。您的示例似乎否定了逻辑,因此1 < 2将计算为False-如果这是您想要的,那么您可以切换逻辑:

if ops[op_string](1, 2):
    print 'False'
# or this...
print(not ops[op_string](1, 2))

或者可以更改运算符映射:

ops = {'<': operator.ge, ...}
print(ops[op_string](1, 2))
# False

使用^{}模块中的函数:

from operator import eq, ne, lt, le, gt, ge

operator_functions = {
    '=': eq,
    '!=': ne,
    '<': lt,
    '<=': le,
    '>': gt,
    '>=': ge,
}

operator = # whatever

if operator_functions[operator](a, b):
    do_whatever()

相关问题 更多 >