중첩 목록 및 사전을 반복하고 모든 정수 여백을 16 진수 문자열로 바꿔야합니다. 이러한 요소는 예를 들어 다음과 같이 수 : 함수를 적용한 후, 그것은 다음과 같아야합니다 중첩 목록 및 사전을 반복하십시오.
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']}, {}]}
을 나는 이미 반복하는 함수를 발견했습니다 중첩 된 iterables http://code.activestate.com/recipes/577982-recursively-walk-python-objects/.
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
을하지만이 기능의 문제는 튜플 요소를 반환한다 : 파이썬 2.5이 기능에 적응는 다음과 같습니다. 그리고 그것들은 편집 할 수 없습니다. 필요한 기능을 구현할 수 있습니까?
안부 wewa
관련 : http://stackoverflow.com/questions/11505304/iterate-over-nested-lists-tuples-and-dictionaries – wewa