我需要迭代嵌套列表和字典,并用十六进制字符串替换每个整数。例如,这样的元素可能如下所示:
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']}, {}]}
我已经找到了一个函数,迭代这些嵌套的iterables 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
答案 0 :(得分:2)
该函数不仅返回元组元素;它返回嵌套结构中任何项的路径,加上它的值。您可以使用该路径获取值并进行更改:
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'}