2015-12-21 39 views
0

我正在構建一個控制pH機器人的應用程序(基於YouTube上的kivy crashcourse)。 build_config函數看起來像:kivy設置:pythonic處理值列表的方式

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 

回答

1

你可以先用剛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] 
+1

很好的提醒lamda函數內的排序 – Moritz

相關問題