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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With