1D列表到复杂的嵌套?压缩为父子关系

时间:2016-11-04 21:55:50

标签: python list parent-child

第一个列表显示行的缩进级别。第二个添加父子关系。使用python如何从第一个到第二个?

indent=[0,1,2,2,2,3,2,3,4,5,5,5,4,2,1,0,1,1]

parent_child=[[0,[1,[2,2,[2,[3]],[2,[3,[4,[5,5,5],4]]],2],1]],[0,[1,1]]]

到目前为止,这是我的代码片段:

pc=[]
for i in indent: 
    if i > pc[i-1]: 
        append
    if i == pc[i-1]: 
        if i+1 > i+1: 
            append
            extend
对我来说,棘手的部分是... 2,[2,[3]]而不是..2,2,[3]

lastindent = -1
print ("open list")
for pos, i in enumerate(indent):
    currchange = i-lastindent
    try:
        nextindent = indent[pos+1]
    except(IndexError):
        print('close all lists')
    nextchange = nextindent-i

    if currchange >0:
        print(" "*i+"open list (rule 1)")
        print(" "*i,i)

    if currchange==0 and nextchange==0:
        print(" "*i+" (rule 2)",i)

    if currchange== 0 and nextchange==1:
        print(" "*i+"open list (rule 3)")
        print(" "*i,i)

    if nextchange < 0:
        print("Close (rule 4)")

    if currchange < 0:
        print ("Close (rule 5")
        print(" "*i,i)
    ##needs more and accurate rules to get the nesting and closing right.

    lastindent = i

一些未完成的插图代码,嵌套的HTML列表可能是一个更好的比较。

0 个答案:

没有答案