我需要遍历嵌套列表和字典,并通过十六进制字符串替换每个整数。例如,这样的元素可能如下所示:
element = {'Request': [16, 2], 'Params': ['Typetext', [16, 2], 2], 'Service': 'Servicetext', 'Responses': [{'State': 'Positive', 'PDU': [80, 2, 0]}, {}]}
应用该功能后,它应该如下所示:
element = {'Request': ['0x10', '0x02'], 'Params': ['Typetext', ['0x10', '0x02'], '0x02'], 'Service': 'Servicetext', 'Responses': [{'State': 'Positive', 'PDU': ['0x50', '0x02', '0x00']}, {}]}
我已经找到了一个函数来迭代这样的嵌套迭代http://code.activestate.com/recipes/577982-recursively-walk-python-objects/。适应 python 2.5 这个函数看起来像这样:
string_types = (str, unicode)
iteritems = lambda mapping: getattr(mapping, 'iteritems', mapping.items)()
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):
for result in objwalk(value, path + (path_component,), memo):
yield result
memo.remove(id(obj))
else:
yield path, obj
但是这个函数的问题是,它返回元组元素。而那些无法编辑。你能帮我实现我需要的功能吗?
最好的问候