如何使用字典调用Python方法
我正在尝试创建一个转换数据的方法列表(或字典)。例如,我有如下数据:如何使用字典调用Python方法,python,python-3.x,dispatch,Python,Python 3.x,Dispatch,我正在尝试创建一个转换数据的方法列表(或字典)。例如,我有如下数据: 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 rul
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_datum
def 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_1
processed_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))
我认为栈上溢出非常接近我要做的,但是我想向有Python经验的人学习如何最好地处理它。我给这篇文章贴上了“发送”的标签,我想这是我想要达到的目标的称呼(?)提前感谢你的帮助和建议 正如评论所说,你们已经非常接近了。您只需在迭代过程中调用
规则
关于处理不同长度的参数,您可以选择在规则中使用*args
和**kwargs
。下面是一个简单的例子:
def rule1(*args, **kwargs):
# Handling of non-keyword params passed in, if any
if args:
for arg in args:
print(f'{arg} is type {type(arg)}')
# if kwargs is not necessary if you don't intend to handle keyword params
def rule2(*args, **kwargs):
# if args is not necessary if you don't intend to handle non-keyword params
# handling of keyword params passed in, if any
if kwargs:
for k, v in kwargs.items():
print(f'Keyword arg {k} has value {v}')
rule_book = [rule2, rule1]
for rule in rule_book:
# iterate through the rule_book with the same amount of args and kwargs
rule('I am a string', 123, ('This', 'is', 'Tuple'), my_list=[0, 1, 2], my_dict={'A': 0, 'B': 1})
结果:
Keyword arg my_list has value [0, 1, 2]
Keyword arg my_dict has value {'A': 0, 'B': 1}
I am a string is type <class 'str'>
123 is type <class 'int'>
('This', 'is', 'Tuple') is type <class 'tuple'>
通过您构建代码的方式,我相信您应该能够理解并将其应用到自己的代码中。很抱歉,我没有回答这个问题,所以您希望将处理后的数据传递给规则书中的所有函数?@alec很抱歉,我的问题让人困惑。我想将
data
中的单个dict
项传递给rule\u book
中的每个规则。然后(通过追加)将其捕获回处理的\u数据中。但是把东西存储回处理过的数据中并不是我问题的重点。我的主要问题是关于如何对单个数据
(即数据
)应用/运行/调用不同的规则方法(可能具有不同的签名/输入参数)。希望这更清楚…是已处理的\u数据。追加(规则(数据))
您在寻找什么?如果您希望在规则之间有不同的参数设置,则很难迭代规则手册
并应用规则。一种方法是在规则中使用*args
或**kwargs
,这样您就可以始终传入相同的参数集,但仅对每个规则使用相关的规则。完全不相关,但此修改的_datum=datum
将不会像您明显期望的那样工作-它不会复制datum
,而是使两个名称指向同一对象。查看此项了解更多详细信息;非常感谢你!这就是我要找的。:)我来这里是想找一些像这里这样的高级解决方案[,但从您那里得到了一个更简单的解决方案,这是完美的。:)您太受欢迎了。愉快的编码!如果您知道您总是在全面传递datum
,您甚至可以在每个规则中将datum
作为静态参数(def rule1(datum,*args,**kwargs):
)避免重复处理。但前提是基准
始终在规则中。
def rule3(*args, **kwargs):
if args:
for arg in args:
if isinstance(arg, tuple):
# if there's a tuple presented, reverse each of the inner items
print([a[::-1] for a in arg])
# ['sihT', 'si', 'elpuT']