[英]How turn this basic list into a more structured one?
我有一个相当基本的清单,如下所示:
listOne = [parentOneObject,childOne,childTwo,childThree,parentTwoObject,childOne,childTwo...]
从严格意义上讲,此列表包含父母和他们旁边的孩子,每个iteml都是该对象(实际上是HTML元素,但这不是问题)
变成一个层次结构,我们得到以下结果:
-ParentOne
-Child1
-Child2
-Child3
-ParentTwo
-Child1
-Child2
等等 ...
为了区分父母,我检查他们的class属性是否包含: level-1
。 其他子项的class属性中具有"level-i"
,其中i
是一个大于1的整数。
我找不到一种方法可以将列表变成更结构化的字典列表,如下所示:
listTwo = [{
'parent' : parentOne,
'children': [childOne,childTwo,childThree]
},
{'parent':parentTwo,
'children': [childOne,childTwo,childThree]
}]
我想使用前面解释的逻辑将第一个基本列表转换成parnet和子对象字典的列表。
我知道我至少应该有一个最低限度的代码,但是对于这个问题,我完全陷入了困境,为此我唯一的代码是:
for item in listOne:
#Do something to turn list one into a structured list
pass
如您所见,没有什么有用的东西,我很乐意在此方面获得一些帮助,而不必是python,因为我被困在逻辑级别,即使伪代码也可以。
您需要一种区分父母与孩子的方法。 然后,您要做的就是循环测试:
listTwo = []
entry = None
for element in listOne:
if isparent(element): # put your test here
entry = {'parent': element, 'children': []}
listTwo.append(entry)
else: # it's a child, append to last parent
entry['children'].append(element)
因此,如果您可以通过HTML类区分HTML元素,则只需进行测试:
if 'level-1' in element.get('class', []): # it's a parent
请注意,如果listOne
的第一个元素不是父元素,则entry['children']
表达式将失败,因为在此阶段entry
仍设置为None
。 这是有意的,您想知道是否有这样的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.