kivy 设置:处理值列表的 pythonic 方式

kivy settings: pythonic way of dealing with list of values

我正在构建一个控制 pH 机器人的应用程序(基于 youtube 上的 kivy crashcourse)。 build_config 函数如下所示:

def build_config(self, config):
    '''
    This function defines the items (like buttons etc.) and their default values. The type, title and description of these items if defined in the file settingsjson.py For each config.setdefault dictionary a json_panel is added in the function build_settings.
    '''
    config.setdefaults(
        'general',
        {'pH_1': False,
        'pH_2': False,
        'pH_3': False,
        'pH_4': False,
        'response_time': 10,
        'base_concentration': 5000,
        'data_path': '/home/moritz/data/'
        })
    config.setdefaults(
        'pump',
        {'some': True 
        })
    config.setdefaults(
        'experiment',
        {'volume_1': 100,
         'volume_2': 100,
         'volume_3': 100,
         'volume_4': 100,
         'buffer_1': 25,
         'buffer_2': 25,
         'buffer_3': 25,
         'buffer_4': 25
        }) 

目前我硬编码了四个 pH 探针。将来应该可以定义探针的数量,并根据该数量更改设置面板(1-8 个探针,动态)。不管探测器的数量是否是硬编码的,我最终都会得到单独的值。稍后,我必须将它们转换为数组。

想法是将 self.config.items 传递给执行 pH 控制部分的程序并转换类似于(伪代码)的项目:

for key in items('general'):
    pH_probes = [item[key].value for key in items('general') if key.startswith('pH')] 

但是,这似乎不是很聪明,因为我必须确保值是有序的 (1-4)。如何以更好的方式做到这一点?

根据接受的答案,我提出了以下解决方案:

def get_config_values(self,section, variable):
    '''
    This section returns  a list of the individual config values for a defined variable for the specified section (e.g 'pH' in section 'general')
    '''
    # get the dictionary for the specified section
    cdict = dict(self.config.items(section))

    # iterate over the keys in the config dictionary, return value if key startswith variable
    # sort them by the last value after the underscore and return a list of the values 
    sorted_list = sorted([value for key, value in d.iteritems() if key.startswith(variable)], key = lambda x: int(x.split('_')[-1]) )
    return sorted_list

您可以先用 pH keys 形成列表,然后对列表进行排序

代码:

dic = {'general':
        {'pH_1': False,
        'pH_2': False,
        'pH_3': False,
        'pH_4': False,
        'response_time': 10,
        'base_concentration': 5000,
        'data_path': '/home/moritz/data/'
        }}
[dic['general'][val] for val in sorted([value for value in dic["general"] if value.startswith("pH")],key = lambda x:int(x[3:]) )]

输出:

[False, False, False, False]