问题描述
I've another question to the thematic of Iterate over nested lists and dictionaries.
我需要一些有关上面链接主题的扩展功能.可迭代元素现在还包含元组.同样,元组中的整数也需要转换为十六进制字符串.因此,我尝试使用以下代码将元组转换为列表.
I need some extended functionality to the topic of the link above. The iterable element now also contains tuples. Also integers in tuples need to be converted to a hex string. Therefor I tried with following code, to convert the tuples to lists.
for path, value in objwalk(element):
if isinstance(value, tuple):
parent = element
for step in path[:-1]:
parent = parent[step]
parent[path[-1]] = list(value)
但是我的问题是,元组中的元组没有被转换.如何以一种优雅的方式将子元组"转换为列表?
But my problem is, that tuples in tuples are not converted. How can I convert "sub-tuples" to lists in an elegant way?
最诚挚的问候威瓦
PS:我创建了一个新主题,因为另一个主题对我来说是固定的.
PS: I created a new topic, because the other-one is fixed for me.
推荐答案
在这种情况下,直接在objwalk
结构遍历器中处理元组会更容易.这是一个修改后的版本,可在将元组遍历以查找嵌套元素之前将其转换为列表:
In this case, it would be easier to handle tuples directly in the objwalk
structure traverser. Here is a modified version that converts tuples to lists before traversing over them to find nested elements:
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):
if isinstance(value, tuple):
obj[path_component] = value = list(value)
for result in objwalk(value, path + (path_component,), memo):
yield result
memo.remove(id(obj))
else:
yield path, obj
使用上一个问题中经过稍微修改的示例,以及我在该问题中为您提供的相同的hex
解决方案:
Using a slightly modified example from your previous question, and the same hex
solution I gave you in that question:
>>> element = {'Request': (16, 2), 'Params': ('Typetext', [16, 2], 2), 'Service': 'Servicetext', 'Responses': ({'State': 'Positive', 'PDU': [80, 2, 0]}, {})}
>>> 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'}
这篇关于遍历嵌套列表,元组和字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!