Home > Enterprise >  Python find value from nested list parent element
Python find value from nested list parent element

Time:07-05

I saved a Parent - Child structure inside a nested list with Python.

PC_List = [[1,1,2],[1,2,8],[1,3,5],[2,4,7],[3,5,1]]

First index of sub list element is ParentID, Second index of sub list element is ChildID, Third index of sub list element is Value

What is the best and fastest way to append the Value from sub list element where childID = current ParentID ? New List should look like this

New_PC_List = [[1,1,2],[1,2,8,2],[1,3,5,2],[2,4,7,8],[3,5,1,5]]

I would appreciate some tipps. P.S. len of PC_List can go over 1Million rows.

Thank you

CodePudding user response:

It was kind of hard to follow what you wanted, but after giving the first element of the list a parent id of 0 (you're using 1-indexing so I assume that's alright), I think this does what you want:

PC_List = [[0,1,2],[1,2,8],[1,3,5],[2,4,7],[3,5,1]]
for i in range(1,len(PC_List)):
    PC_List[i].append(PC_List[PC_List[i][0]-1][2])

This solution changes the original list, but this can be fixed with copy.deepcopy if you prefer.

CodePudding user response:

I would first construct a dict that maps "id" to the "value", and then use it to append the values.

PC_List = [[1,1,2],[1,2,8],[1,3,5],[2,4,7],[3,5,1]]
values = {k: v for _, k, v in PC_List}

output = [[p, c, v, values[p]] for p, c, v in PC_List]
print(output)
# [[1, 1, 2, 2], [1, 2, 8, 2], [1, 3, 5, 2], [2, 4, 7, 8], [3, 5, 1, 5]]
  • Related