2016-07-09 37 views
0

我有一個非常基本的列表如下所示:如何將這個基本列表變成更加結構化的列表?

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

Sementically,這個列表中包含的父母和他們的孩子在他們旁邊,每個iteml是這個名單是一個對象(一個HTML元素,在現實中,但這是不是

化作一個層次的問題),我們得到這樣的:

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

等等......

要解散如果它含有:level-1,我檢查他們的班級屬性。其他孩子的班級屬性中有"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,因爲我被困在邏輯層面,即使僞代碼也沒問題。

+0

如何確定父母? – galaxyan

+0

那麼你如何區分父母與孩子? –

+0

在class屬性中它們有這個「level-1」,這意味着父母,childs有「level-i」,其中i是一個整數(不是1)。我應該把它加到OP中 – Souames

回答

2

你需要有一種方法來區分父母與孩子。然後,所有你需要做的就是在一個循環測試爲:

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。這是故意的,你想知道你是否有這樣的錯誤。