遍历嵌套列表和字典 [英] Iterate over nested lists and dictionaries
问题描述
我需要遍历嵌套列表和字典,并用十六进制字符串替换每个整数.例如,这样的元素可能看起来像这样:
I need to iterate over nested lists and dictionaries and replace every integer trough an hex string. Such an element could for example look like this:
element = {'Request': [16, 2], 'Params': ['Typetext', [16, 2], 2], 'Service': 'Servicetext', 'Responses': [{'State': 'Positive', 'PDU': [80, 2, 0]}, {}]}
应用该函数后,它应如下所示:
After after applying the function, it should look like this:
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时,此函数如下所示:
I've already found a function, to iterate over such nested iterables http://code.activestate.com/recipes/577982-recursively-walk-python-objects/. Adapted to python 2.5 this function looks like this:
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
但是此函数的问题在于,它返回元组元素.并且那些不能被编辑. 您能帮我实现我需要的功能吗?
But the problem with this function is, that it returns tuple elements. And those can't be edited. Can you help me to implement a function I need?
最诚挚的问候 威瓦
推荐答案
该函数不仅返回元组元素,还返回元组元素.它返回嵌套结构中任何项目的路径及其值.您可以使用该路径获取值并对其进行更改:
The function doesn't just return tuple elements; it returns the path to any item in the nested structure, plus it's value. You can use that path to get at the value and change it:
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)
因此,对于每个整数值,请使用路径查找该值的父级,然后将其替换为十六进制等效值.
So, for every value that is an integer, use the path to find the parent of that value, then replace the current value with it's hex equivalent.
您从上述方法获得的输出:
The output you get from the above method:
>>> element
{'Params': ['Typetext', ['0x10', '0x2'], '0x2'], 'Request': ['0x10', '0x2'], 'Responses': [{'State': 'Positive', 'PDU': ['0x50', '0x2', '0x0']}, {}], 'Service': 'Servicetext'}
这篇关于遍历嵌套列表和字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!