开发者

Grouping Elements of Lists Within a List by Index

I am t开发者_如何学JAVArying to take a list of lists, and return a list of lists which contain each element at an index of the original list of lists. I know that that's badly worded. Here's an example.

Say I have the following list of lists:

[[1,2,3], [4,5,6], [7,8,9]]

I want to get another list of lists, in which each list is a list of each elements at a specific index. For example:

[[1,2,3], [4,5,6], [7,8,9]] becomes [[1,4,7], [2,5,8], [3,6,9]]

So the first list in the returned list, contains all of the elements at the first index of each of the original list, and so on. I'm stuck, and have no idea how this could be done. Any help would be appreciated. Thanks.


>>> [list(t) for t in zip(*[[1,2,3], [4,5,6], [7,8,9]])]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]


perhaps an easy way wiould be:

a=[[1,2,3], [4,5,6], [7,8,9]]
b=zip(*a)

b will be equal to [(1, 4, 7), (2, 5, 8), (3, 6, 9)]. hopes this helps


Dan D's answer is correct and will work in Python 2.x and Python 3.x.

If you're doing lots of matrix operations, not just transposition, it's worth considering Numpy at this juncture:

>>> import numpy as np
>>> x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> np.swapaxes(x, 0, 1)
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])

Or, more simply, as per the comments, use numpy.transpose():

>>> np.transpose(x)
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])


In addition to the zip(*lists) approach, you could also use a list comprehension:

[[l[i] for l in lists] for i in range(3)]


In case you want to simply transpose your matrix -e.g. to get new matrix where rows are cols from initial matrix while columns equal to the initial matrix rows values then you can use:

initMatr = [
            [1,2,3],
            [4,5,6],
            [7,8,9]
           ]
map(list, zip(*initMatr))


>>> [
     [1,4,7],
     [2,5,8],
     [3,6,9]
    ]

OR in case you want to rotate matrix left then:

map(list, zip(*map(lambda x: x[::-1], initMatr)

>>> [
       [3,6,9],
       [2,5,8],
       [1,4,7]       
    ]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜