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
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]]