我试图通过使用python解决练习,我想我解决了它。当我使用我的功能进行单一测试时效果很好。但当它的多次检查我得到错误。每个函数保存结果都是相同的字典。我试着阅读关于变量的可见性,但我一无所获。请给我一个链接,我在哪里可以阅读这个主题。
def flatten(dicts, a='', free={}):
for k, v in dicts.iteritems():
if a in dicts.keys():
a = ""
if a != "":
b = "/"
else:
b = ""
if isinstance(v, dict):
if len(v.keys()) == 0:
free[a+b+k] = ""
else:
a += b+k
flatten(v, a)
else:
free[a+b+k] = v
return free
print flatten({"key": "value"}) == {"key": "value"}
print flatten({"key": {"deeper": {"more": {"enough": "value"}}}}) == {"key/deeper/more/enough": "value"}
print flatten({"name": {
"first": "One",
"last": "Drone"},
"job": "scout",
"recent": {},
"additional": {
"place": {
"zone": "1",
"cell": "2"}}}
) == {"name/first": "One",
"name/last": "Drone",
"job": "scout",
"recent": "",
"additional/place/zone": "1",
"additional/place/cell": "2"}
我最终得到了这个:
{'key/deeper/more/enough': 'value', 'additional/place/zone': '1',
'job': 'scout', 'additional/place/cell': '2', 'name/first': 'One',
'name/last': 'Drone', 'key': 'value', 'recent': ''}