Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a 2 dimensional array or a list into two 1 dimensional lists in python [duplicate]

You have a 2-Dimensional list of numbers like:

x = [[1,2],[3,4],[5,6],[7,8],[9,10],[11,12],[13,14],[15,16],[17,18]]

You need to split it into two lists in such a way that you get the numbers from the first column in one list and the second column in another list:

[1,3,5,7,9,11,13,15,17] [2,4,6,8,10,12,14,16,18]

How can that be done in python?

I am posting this question because I could not find a simple answer to it. I will be answering it later.

like image 323
aabb bbaa Avatar asked Dec 20 '16 18:12

aabb bbaa


Video Answer


2 Answers

It is the ideal case of using zip as:

>>> x = [[1,2],[3,4],[5,6],[7,8],[9,10],[11,12],[13,14],[15,16],[17,18]]

#       v unpack `x` list
>>> zip(*x)
[(1, 3, 5, 7, 9, 11, 13, 15, 17), (2, 4, 6, 8, 10, 12, 14, 16, 18)]

Returned value is a list of two tuples. In order to save each tuple in variable, you may do:

>>> a, b = zip(*x)
like image 52
Moinuddin Quadri Avatar answered Sep 27 '22 19:09

Moinuddin Quadri


In [27]: x = [[1,2],[3,4],[5,6],[7,8],[9,10],[11,12],[13,14],[15,16],[17,18]]

In [28]: first, second = zip(*x)

In [29]: first
Out[29]: (1, 3, 5, 7, 9, 11, 13, 15, 17)

In [30]: second
Out[30]: (2, 4, 6, 8, 10, 12, 14, 16, 18)
like image 39
inspectorG4dget Avatar answered Sep 27 '22 18:09

inspectorG4dget