【问题标题】:Iterate over nested lists and dictionaries迭代嵌套列表和字典
【发布时间】:2012-07-16 09:04:01
【问题描述】:

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

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

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

最好的问候 哇

【问题讨论】:

标签: python loops


【解决方案1】:

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

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'}

【讨论】:

猜你喜欢
  • 2012-07-15
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 2016-02-13
  • 2021-11-29
相关资源
最近更新 更多