Home > database >  Reshaping Lists /Arrays
Reshaping Lists /Arrays

Time:11-03

I have the following list :

initial_list =[[[1],[11]],[[2],[12]],[[3],[13]],[[4],[14]],[[5],[15]]] 

and I want to converted the initial_list to the following list:

new_list = [[1, 2, 3, 4, 5], [11, 12, 13, 14, 15]]

Any ideas?

Thanks.

CodePudding user response:

You can use zip and itertools.chain like below:

>>> from itertools import chain
>>> lst =[[[1],[11]],[[2],[12]],[[3],[13]],[[4],[14]],[[5],[15]]]
>>> list(map(list,map(chain.from_iterable,zip(*lst))))
[[1, 2, 3, 4, 5], [11, 12, 13, 14, 15]]

# for more explanation
>>> list(zip(*lst))
[([1], [2], [3], [4], [5]), ([11], [12], [13], [14], [15])]

>>> list(chain.from_iterable(list(zip(*lst))[0]))
[1, 2, 3, 4, 5]

CodePudding user response:

Using zip and iter:

>>> initial_list = [[[1],[11]],[[2],[12]],[[3],[13]],[[4],[14]],[[5],[15]]]
>>> [list(map(next, map(iter, i))) for i in zip(*initial_list)]
[[1, 2, 3, 4, 5], [11, 12, 13, 14, 15]]
  • Related