我需要迭代嵌套列表和字典,並用十六進制字符串替換每個整數。這樣的元件例如可以是這樣的: 迭代嵌套列表和字典
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
相關:http://stackoverflow.com/questions/11505304/iterate-over-nested-lists-tuples-and-dictionaries – wewa 2012-07-17 05:18:51