greole
greole

Reputation: 4771

Reordering Nested List Entries in Python

is there any shortcut to regroup a nested list like

[[a0,b0,c0],[a1,b1,c1],[a2,b2,b2]]

to give something like this

 [[a0,a1,a2],[b0,b1,b2],[c0,c1,c2]]

Upvotes: 3

Views: 95

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121992

Yes, using zip():

transposed = zip(*matrix)

*matrix applies all nested lists in matrix as separate arguments to the zip() function, as if you typed zip(matrix[0], matrix[1], matrix[2]); zip() takes input sequences and outputs new sequences per column.

Demo:

>>> matrix = [['a0', 'b0', 'c0'], ['a1', 'b1', 'c1'], ['a2', 'b2', 'b2']]
>>> zip(*matrix)
[('a0', 'a1', 'a2'), ('b0', 'b1', 'b2'), ('c0', 'c1', 'b2')]

The output uses nested tuples; if you require nested lists, transform them after the fact with:

map(list, zip(*matrix))

or

[list(t) for t in zip(*matrix)]

Upvotes: 5

Related Questions