How to zip the elements of a single nested list

javadba :

Consider a nested list:

d = [[1,2,3],[4,5,6]]                                                                                                                                                                                                                                                  

I want to zip its elements for this result:

 [[1,4],[2,5],[3,6]]

How to do that? An incorrect approach is

list(zip(d))

But that gives:

[([1, 2, 3],), ([4, 5, 6],)]

What is the correct way to do the zip ?

tim :

You need to give the single sub-lists via unpacking (*) as single arguments to zip() like this:

d = [[1,2,3],[4,5,6]]          
zip(*d)  # You need this one
[(1, 4), (2, 5), (3, 6)]

This even works for longer lists, in case this is the behaviour you want:

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

If you want to have a list of lists instead of a list of tuples, just do this:

map(list, zip(*d))
[[1, 4], [2, 5], [3, 6]]

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=8142&siteId=1