0
我创建了一个应该将嵌套列表转换为字典的类。以下是我输入:递归修改字典
['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'}
_我的方法没有做它应该做的事那么它在做什么呢? –
@JohnGordon:编辑添加输出,谢谢! – PepperoniPizza
可能是https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ –