迭代嵌套列表和字典

2023-11-27

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

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

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

此致 韦瓦


该函数不仅返回元组元素,还返回元组元素。它返回嵌套结构中任何项目的路径及其值。您可以使用该路径获取该值并更改它:

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'}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

迭代嵌套列表和字典 的相关文章

随机推荐