迭代嵌套列表和字典

wew*_*ewa 5 python loops

我需要遍历嵌套列表和字典,并通过十六进制字符串替换每个整数。例如,这样的元素可能如下所示:

element = {'Request': [16, 2], 'Params': ['Typetext', [16, 2], 2], 'Service': 'Servicetext', 'Responses': [{'State': 'Positive', 'PDU': [80, 2, 0]}, {}]}
Run Code Online (Sandbox Code Playgroud)

应用该函数后,它应该是这样的:

element = {'Request': ['0x10', '0x02'], 'Params': ['Typetext', ['0x10', '0x02'], '0x02'], 'Service': 'Servicetext', 'Responses': [{'State': 'Positive', 'PDU': ['0x50', '0x02', '0x00']}, {}]}
Run Code Online (Sandbox Code Playgroud)

我已经找到了一个函数,可以遍历这种嵌套的可迭代对象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
Run Code Online (Sandbox Code Playgroud)

但是这个函数的问题是,它返回元组元素。而那些是无法编辑的。你能帮我实现一个我需要的功能吗?

最好的问候wewa

Mar*_*ers 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)
Run Code Online (Sandbox Code Playgroud)

因此,对于每个整数值,使用路径查找该值的父级,然后将当前值替换为其等效的十六进制值。

从上述方法得到的输出:

>>> element
{'Params': ['Typetext', ['0x10', '0x2'], '0x2'], 'Request': ['0x10', '0x2'], 'Responses': [{'State': 'Positive', 'PDU': ['0x50', '0x2', '0x0']}, {}], 'Service': 'Servicetext'}
Run Code Online (Sandbox Code Playgroud)