Reputation: 7504
Suppose I have a list like this:
[[1, 2], [2, 3], [5, 4]]
What I want is two different lists from the above list with first element in one list and
the second element in the other.
The result will look like this:
[1,2,5] and [2,3,4]
Is there any way to do it by using list splicing ?
Upvotes: 1
Views: 44
Reputation: 1121494
Use zip()
to pair up the elements of the input lists:
lista, listb = zip(*inputlist)
The *
applies the elements in inputlist
as separate arguments, as if you called zip()
as zip([1, 2], [2, 3], [5, 4])
. zip()
takes the first element of each argument and returns those together, and then the second element, etc.
This produces tuples, not lists, really, but that's easy to remedy:
lista, listb = map(list, zip(*inputlist))
Demo:
>>> inputlist = [[1, 2], [2, 3], [5, 4]]
>>> zip(*inputlist)
[(1, 2, 5), (2, 3, 4)]
>>> lista, listb = map(list, zip(*inputlist))
>>> lista
[1, 2, 5]
>>> listb
[2, 3, 4]
Upvotes: 2
Reputation: 214927
How about use numpy
array?
import numpy as np
np.array(myList).transpose()
# array([[1, 2, 5],
# [2, 3, 4]])
Or
np.array(myList)[:, 0]
# array([1, 2, 5])
np.array(myList)[:, 1]
# array([2, 3, 4])
Upvotes: 1