简体   繁体   English

如何将这个基本列表变成一个结构化的列表?

[英]How turn this basic list into a more structured one?

I have a fairly basic list as the following : 我有一个相当基本的清单,如下所示:

listOne = [parentOneObject,childOne,childTwo,childThree,parentTwoObject,childOne,childTwo...]

Sementically, this list contains parents and their child next to them, each iteml is this list is an object (An HTML Element, in reality, but this is not a problem) 从严格意义上讲,此列表包含父母和他们旁边的孩子,每个iteml都是该对象(实际上是HTML元素,但这不是问题)

Turned into a hierarchy, we get this : 变成一个层次结构,我们得到以下结果:

-ParentOne
  -Child1
  -Child2
  -Child3
-ParentTwo
  -Child1
  -Child2

And so on ... 等等 ...

To distinguish parents, I check their class attribute if it contains : level-1 . 为了区分父母,我检查他们的class属性是否包含: level-1 Other childs have "level-i" in their class attribute, where i is an integer bigger then one . 其他子项的class属性中具有"level-i" ,其中i是一个大于1的整数。

I can't find a way to turn that list into a more structured list of dict like this: 我找不到一种方法可以将列表变成更结构化的字典列表,如下所示:

listTwo = [{
            'parent' : parentOne,
            'children': [childOne,childTwo,childThree]
            },
            {'parent':parentTwo,
             'children': [childOne,childTwo,childThree]
            }]

I want to turn the first basic list into a list of dictionaries of parnet and children objects using the logic explained previously . 我想使用前面解释的逻辑将第一个基本列表转换成parnet和子对象字典的列表。

I know that I should have at least a minimum code, but for this problem I'm totally stuck, the only code I have for this is : 我知道我至少应该有一个最低限度的代码,但是对于这个问题,我完全陷入了困境,为此我唯一的代码是:

for item in listOne:
   #Do something to turn list one into a structured list
   pass

As you can see nothing useful, I'd love to get some help on this, doesn't have to be python, because I'm stuck at the logic level, even pseudocode is fine . 如您所见,没有什么有用的东西,我很乐意在此方面获得一些帮助,而不必是python,因为我被困在逻辑级别,即使伪代码也可以。

You need to have a way to distinguish parents from children. 您需要一种区分父母与孩子的方法。 Then all you have to do is test for that in a loop: 然后,您要做的就是循环测试:

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)

So if you can distinguish your HTML elements by a HTML class, then just test for that: 因此,如果您可以通过HTML类区分HTML元素,则只需进行测试:

if 'level-1' in element.get('class', []):  # it's a parent

Note that if the first element in listOne is not a parent element, the entry['children'] expression will fail as entry is still set to None at that stage. 请注意,如果listOne第一个元素不是父元素,则entry['children']表达式将失败,因为在此阶段entry仍设置为None This is deliberate, you'd want to know if you had an error like that. 这是有意的,您想知道是否有这样的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM