我创建了一个类,可以将嵌套列表转换为字典。以下是我的输入:
['function:and',
['variable:X', 'function:>=', 'value:13'],
['variable:Y', 'function:==', 'variable:W']]
并且输出应该是以下形式的字典:
{
"function": "and",
"args": [
{
"function": ">=",
"args": [
{
"variable": "X"
},
{
"value": 13
}
]
},
{
"function": "==",
"args": [
{
"variable": "Y"
},
{
"variable": "W"
}
]
}
]
}
这是接收输入列表并返回所需字典的类。
class Tokenizer(object):
def __init__(self, tree):
self.tree = tree
self.filter = {}
def to_dict(self, triple):
my_dict = {}
try:
first = triple[0]
second = triple[1]
third = triple[2]
except KeyError:
return
if type(second) == str and type(third) == str:
my_dict['function'] = second.split(':')[-1]
my_dict['args'] = [
{first.split(':')[0]: first.split(':')[1]},
{third.split(':')[0]: third.split(':')[1]}]
# case recursive
if type(second) == list:
my_dict['function'] = first.split(':')[-1]
my_dict['args'] = [second, third]
return my_dict
def walk(self, args):
left = self.to_dict(args[0])
right = self.to_dict(args[1])
if isinstance(left, dict):
if 'args' in left.keys():
left = self.walk(left['args'])
if isinstance(right, dict):
if 'args' in right.keys():
right = self.walk(right['args'])
args = [left, right]
return args
def run(self):
self.filter.update(self.to_dict(self.tree))
if 'args' in self.filter.keys():
self.filter['args'] = self.walk(self.filter['args'])
tree = [
'function:and',
['variable:X', 'function:>=', 'value:13'],
['variable:Y', 'function:==', 'variable:W']
]
import pprint
pp = pprint.PrettyPrinter(indent=4)
t = Tokenizer(tree)
t.run()
pp.pprint(t.filter)
我的递归方法 walk
没有做它应该做的事情,我完全是递归的傻瓜,所以我不知道我做错了什么。
我得到的输出是:
{ 'args': [[None, None], [None, None]], 'function': 'and'}
最佳答案
对于您的特定测试用例,您根本不需要进行递归。您可以注释掉您的通话:
def walk(self, args):
left = self.to_dict(args[0])
right = self.to_dict(args[1])
#if isinstance(left, dict):
# if 'args' in left.keys():
# left = self.walk(left['args'])
#if isinstance(right, dict):
# if 'args' in right.keys():
# right = self.walk(right['args'])
args = [left, right]
return args
并获得所需的输出。 如果您允许在输入中使用嵌套函数,则只需要进入递归:
['function:and',
['variable:X', 'function:>=', 'value:13'],
['function:==',
['variable:R', 'function:>=', 'value:1'],
['variable:Z', 'function:==', 'variable:K']
]
]
然后您必须检查基本情况,因此仅当您的 args
键的值包含未处理的值时才进入递归:
def walk(self, args):
left = self.to_dict(args[0])
right = self.to_dict(args[1])
if isinstance(left, dict):
if 'args' in left.keys() and isinstance(left['args'][0], list):
left = self.walk(left['args'])
if isinstance(right, dict):
if 'args' in right.keys() and isinstance(right['args'][0], list):
right = self.walk(right['args'])
args = [left, right]
return args
然后你会得到这个:
{ 'args': [ { 'args': [{ 'variable': 'X'}, { 'value': '13'}],
'function': '>='},
{ 'args': [ { 'args': [ { 'variable': 'R'},
{ 'value': '1'}],
'function': '>='},
{ 'args': [ { 'variable': 'Z'},
{ 'variable': 'K'}],
'function': '=='}],
'function': '=='}],
'function': 'and'}
此外,如果您的输入列表是一个常规结构,在函数名称字段之后始终具有参数字段,那将会更容易。然后,您可以显着简化您的 to_dict
方法。
关于python - 递归修改字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39861433/