Skip to main content
 首页 » 编程设计

Python 比较评估器替换

2025年05月04日24lvdongjie

我想根据字符串的上下文替换比较标记。我在 Python 3.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. 

或者,如果这是不可能的,有没有人有任何解决方案来避免每个分支都有大量的、包罗万象的“if”语句 block ?我计划在 line 中放一些指令,最终用正确的 python 等价物代替,例如 "=" 而不是正确的 "==".

提前致谢!

请您参考如下方法:

使用 operator 中的函数模块:

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()