Reputation: 11
Here is what I am trying to do cleanly. I have the following list of list
lst1 = [[1,2,3],[4,5,6],[7,8,9]]
Now I want to generate the following list
lst2 = [[1,4,7],[2,5,8],[3,6,9]]
Now I know I can come close to lst2 as follows
lst2 = zip[lst1[0],lst1[1],lst1[2]]
lst2 = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
and then with a for loop generate my new list of list.
Is there a method to generate the new list when the size of the original list is not known.
lst1 = [[0],[1], ... [n]]
lst2 = [[0],[2], ... [n]]
I have spent too much time researching and trying to figure out this problem. This process is really not need by be since I am only working with a list of 3 lists. (Exp. lst1). My curiosity has gotten the better of me. Hope someone has a solution because I have hit a brick wall at this point.
Upvotes: 1
Views: 50
Reputation: 12879
If you want a list of lists (and not a list of tuples), then you could use a list comprehension with the zip() built-in:
>>> l = [[1,2,3],[4,5,6],[7,8,9]]
>>> [list(x) for x in zip(*l)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Upvotes: 1
Reputation: 46759
All you need is:
lst1 = [[1,2,3],[4,5,6],[7,8,9]]
print zip(*lst1)
Giving:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
By adding the *
, it tells Python to unpack the list as separate arguments to the function. See Unpacking Argument Lists.
Upvotes: 1