0

Can someone help me split a list into two

Example of a list:

[[[9.0, 16.0], [11.0, 15.0], [12.0, 16.0], [14.0, 13.0]], [[22.0, 13.0], [23.0, 14.0]]]

Output:

A=[9.0, 11.0, 12.0, 14.0, 22.0, 23.0]
B=[16.0, 15.0, 16.0, 13.0, 13.0, 14.0]

1 Answers1

1

You can use chain then split to two list like below:

>>> from itertools import chain
>>> lst = [[[9.0, 16.0], [11.0, 15.0], [12.0, 16.0], [14.0, 13.0]], [[22.0, 13.0], [23.0, 14.0]]]

>>> lst = list(chain.from_iterable(lst))
>>> lst
[[9.0, 16.0],
 [11.0, 15.0],
 [12.0, 16.0],
 [14.0, 13.0],
 [22.0, 13.0],
 [23.0, 14.0]]
    
>>> [l[0] for l in lst]
[9.0, 11.0, 12.0, 14.0, 22.0, 23.0]


>>> [l[1] for l in lst]
[16.0, 15.0, 16.0, 13.0, 13.0, 14.0]

By thanks @PeterWood you can use zip like below:

>>> from itertools import chain
>>> lst = [[[9.0, 16.0], [11.0, 15.0], [12.0, 16.0], [14.0, 13.0]], [[22.0, 13.0], [23.0, 14.0]]]
>>> lst = chain.from_iterable(lst)

>>> A, B = list(zip(*lst))
>>> list(A)
[9.0, 11.0, 12.0, 14.0, 22.0, 23.0]

>>> list(B)
[16.0, 15.0, 16.0, 13.0, 13.0, 14.0]
I'mahdi
  • 23,382
  • 5
  • 22
  • 30