迭代嵌套列表和字典

迭代嵌套列表和字典

问题描述:

我需要迭代嵌套列表和字典,并用十六进制字符串替换每个整数。这样的元件例如可以是这样的: 迭代嵌套列表和字典

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

+0

相关:http://*.com/questions/11505304/iterate-over-nested-lists-tuples-and-dictionaries – wewa 2012-07-17 05:18:51

的功能不只是返回的元组元素;它将返回嵌套结构中任何项目的路径以及其值。您可以使用路径来获得的值,并将其更改:

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

非常感谢你很多Martijn。 – wewa 2012-07-16 09:38:48

+0

你有胶水如何解决这个问题:http://*.com/questions/11505304/iterate-over-nested-lists-tuples-and-dictionaries? – wewa 2012-07-16 14:07:58