我正在尝试创建一个转换数据的方法列表(或字典)。例如,我有如下数据:data = [{'Result': 1, 'Reason1': False, 'Reason2': 1},{'Result': 0, 'Reason1': False, 'Reason2':'haha'},{'Result': 0, 'Reason1': True, 'Reason2': 'hehe'},{'Result': 0, 'Reason1': True, 'Reason2': 0},]def rule_1(datum): modified_datum = datum if datum['Reason1']: modified_datum['Result'] = 1 # always set 'Result' to 1 whenever 'Reason1' is True else: modified_datum['Result'] = 1 # always set 'Result' to 0 whenever 'Reason1' is False return modified_datumdef rule_2(datum): modified_datum = datum if type(datum['Reason2']) is str: modified_datum['Result'] = 1 # always set 'Result' to 1 whenever 'Reason2' is of type 'str' elif type(datum['Reason2']) is int: modified_datum['Result'] = 2 # always set 'Result' to 2 whenever 'Reason2' is of type 'int' else: modified_datum['Result'] = 0 return modified_datum# There can be 'rule_3', 'rule_4' and so on... Also, these rules may have different method signatures (that is, they may take in more than one input parameter)rule_book = [rule_2, rule_1] # I want to apply rule_2 first and then rule_1processed_data = []for datum in data: for rule in rule_book: # Like someone mentioned here, the line below works, but what if I want to have different number of input parameters for rule_3, rule_4 etc.? # processed_data.append(rule(datum))我认为Stack Overflow 上的这个答案与我想要做的非常接近,但我想向有 Python 经验的人学习如何最好地处理它。我用“调度”标记了这篇文章,我认为这是我试图实现的目标(?)的术语,谢谢您的帮助和建议!
添加回答
举报
0/150
提交
取消