Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reordering Nested List Entries in Python

Tags:

python

list

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]]
like image 748
greole Avatar asked Jul 23 '26 19:07

greole


1 Answers

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)]
like image 56
Martijn Pieters Avatar answered Jul 25 '26 11:07

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!