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/ –