objwalk
在这种情况下,直接在结构遍历器中处理元组会更容易。这是一个修改后的版本,它在遍历元组以查找嵌套元素之前将其转换为列表:
def objwalk(obj, path=(), memo=None):
if memo is None:
memo = set()
iterator = None
if isinstance(obj, dict):
iterator = iteritems
elif isinstance(obj, (list, set)) and not isinstance(obj, string_types):
iterator = enumerate
if iterator:
if id(obj) not in memo:
memo.add(id(obj))
for path_component, value in iterator(obj):
if isinstance(value, tuple):
obj[path_component] = value = list(value)
for result in objwalk(value, path + (path_component,), memo):
yield result
memo.remove(id(obj))
else:
yield path, obj
使用您上一个问题中稍作修改的示例,以及hex
我在该问题中给您的相同解决方案:
>>> element = {'Request': (16, 2), 'Params': ('Typetext', [16, 2], 2), 'Service': 'Servicetext', 'Responses': ({'State': 'Positive', 'PDU': [80, 2, 0]}, {})}
>>> for path, value in objwalk(element):
... if isinstance(value, int):
... parent = element
... for step in path[:-1]:
... parent = parent[step]
... parent[path[-1]] = hex(value)
...
>>> element
{'Params': ['Typetext', ['0x10', '0x2'], '0x2'], 'Request': ['0x10', '0x2'], 'Responses': [{'State': 'Positive', 'PDU': ['0x50', '0x2', '0x0']}, {}], 'Service': 'Servicetext'}