Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restructure nested python lists

Let's say we have a nested list with 3 levels (D1=2,D2=3,M=2), like:

l = [[[1,a],[2,b],[3,c]], [[4,d],[5,e],[6,f]]]

I'm trying to figure out if there is any pythonic way to build 2 new nested lists with 2 levels (D1=2,D2=3), like:

l1 = [[1,2,3], [4,5,6]]
l2 = [[a,b,c], [d,e,f]]

Then we may have N levels and the lists in the deepest level contain M elements (D1,D2,D3, ..., D_N-1,M), the goal is always to build nested M lists with N-1 levels.

In other words we need to retain the hierarchy by splitting the lower level.

Other example:

l = [[[[13076, 0, 0], [806, 0, 0]], [[13076, 0, 0], [2, 0, 0]]]], [[[[2066, 0, 0], [8, 0, 0]], [[42, 0, 0], [4147, 0, 0]]]]

l1 = [[[13076,806], [13076,2]], [[2066,8],[42,4147]]]
l2 = [[[0,0], [0,0]], [[0,0], [0,0]]]
l3 = [[[0,0], [0,0]], [[0,0], [0,0]]]
like image 467
kiddo Avatar asked Sep 23 '26 09:09

kiddo


2 Answers

numpy syntax is convenient for this task:

import numpy as np

l = [[[1, 'a'], [2, 'b'], [3, 'c']],
     [[4, 'd'], [5, 'e'], [6, 'f']]]

a = np.array(l)

l1 = a[:, :, 0].astype(int).tolist()

# [[1, 2, 3], [4, 5, 6]]

l2 = a[:, :, 1].tolist()

# [['a', 'b', 'c'], ['d', 'e', 'f']]
like image 102
jpp Avatar answered Sep 25 '26 00:09

jpp


You simply do :

l1=[[i[0] for i in j] for j in l]
l2=[[i[1] for i in j] for j in l]
like image 43
Dadep Avatar answered Sep 25 '26 00:09

Dadep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!