创建pythonic变量ifelsestructure

2024-10-02 00:44:01 发布

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

我正在寻找一种从用户输入在python中创建变量if else结构的方法。 我有以下例子:

measVals = {'time': [400,500,...],'volt': [12.5,12.0,...], 'current': [500,350,...]}

静态if elif else结构:

if measVals['time'][0] <= 400 and measVals['volt'][0] > 8:
    if measVals['volt'][1] < 20:
        minMaxValues = {'current': {'min':0, 'max': 50}}
    elif measVals['volt'][1] < 12:
        minMaxValues = {'current': {'min':0, 'max': 100}}
elif measVals['time'][0] >= 500
    minMaxValues = {'current': {'min':0, 'max': 500}}
    

现在,另一个用户希望根据他的测量值定义自己的标准和MinMaxValue, 所以if-elif-else的结构可能与我的完全不同

我的目标是将该数据作为代码的参数读入,这样我就不必更改 定义新标准等时的代码:

                                |   
                                | measVals
User defined criteria        ___V___        
------------------------->  |       |   
                            |       |
User defined minMaxValues   |  Code |
------------------------->  |       |   
                            |_______|
                                |
                                | correct minMaxValue dict
                                V
                            

用户测量值:

measVals = {'time': [0,10,...],'temp': [23,23,...], 'pressure1': [500,350,...],'pressure2': [0,20,...]}
                            

用户定义标准和相应的最小/最大值(伪代码):

    crit_1 = 'measVals['time'][0] <= 50' 
         .
         .
         .
    crit_1x = 'any condition' -> {'pressure1': {'max': 500,'min': 0},
                                  'pressure2': {'max': 50,'min': 0}}
    crit_2 = 'any condition' 
    crit = 'measVals['temp'][2] < 30'-> {'pressure1': {'max': 300, 'min': 0},
                                         'pressure2': {'max': 0,'min': 0}}
    crit_x = 'any condition'
         .
         .
         .
    crit_xx = 'any condition' -> {'pressure1': {'max': w, 'min': x},
                                  'pressure2': {'max': y,'min': z}}

因此,我的想法是(例如,使用gui)将用户定义的数据读入一个嵌套字典,其中标准为键,MinMaxValue位于最低级别,如下所示:

criteriaMinMaxDict = 
{'measVals['time'][0] <= 50': {crit_1x: {'pressure1': {'max': 500,'min': 0},
                                         'pressure2': {'max': 50,'min': 0}}},
 crit_2: {'measVals['temp'][2] < 30': {'pressure1': {'max': 300, 'min': 0},
                                       'pressure2': {'max': 0,'min': 0}}},
 crit_x: {crit_xx: {'pressure1': {'max': w, 'min': x},
                    'pressure2': {'max': y,'min': z}}}}
 

有了这个指令,我必须结合递归使用eval(key)来获得正确的minmaxvalue。 这是可行的,但看起来非常错误,尤其是作为键的条件字符串

有没有人有更好(更像Python)的方法来解决这类问题

提前谢谢


Tags: 用户标准iftimeanycurrentminmax

热门问题