我需要遍历嵌套的列表和字典,并将每个整数替换为十六进制字符串。例如,这样的元素可能如下所示:
应用该函数后,其效果应如下:
但是这个函数的问题是它返回元组元素,而这些元素是无法编辑的。你能帮我实现我需要的函数吗?
最好的问候, wewa
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
但是这个函数的问题是它返回元组元素,而这些元素是无法编辑的。你能帮我实现我需要的函数吗?
最好的问候, wewa