Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpose nested list in python

Tags:

python

list

I like to move each item in this list to another nested list could someone help me?

a = [['AAA', '1', '1', '10', '92'], ['BBB', '262', '56', '238', '142'], ['CCC', '86', '84', '149', '30'], ['DDD', '48', '362', '205', '237'], ['EEE', '8', '33', '96', '336'], ['FFF', '39', '82', '89', '140'], ['GGG', '170', '296', '223', '210'], ['HHH', '16', '40', '65', '50'], ['III', '4', '3', '5', '2']]

On the end I will make list like this:

[['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF'.....],
['1', '262', '86', '48', '8', '39', ...],
['1', '56', '84', '362', '33', '82', ...],
['10', '238', '149', '205', '96', '89', ...],
...
...]
like image 499
Robert Avatar asked Jan 29 '14 22:01

Robert


People also ask

How do you transpose a nested list in Python?

In this, we initialize a new empty list called row. We then loop over each ith item and append to our list row. Finally, we append that row to our transposed list.

How do you transpose a list in Python?

Transpose with built-in function zip() You can transpose a two-dimensional list using the built-in function zip() . zip() is a function that returns an iterator that summarizes the multiple iterables ( list , tuple , etc.). In addition, use * that allows you to unpack the list and pass its elements to the function.


2 Answers

Use zip with * and map:

>>> map(list, zip(*a))
[['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF', 'GGG', 'HHH', 'III'],
 ['1', '262', '86', '48', '8', '39', '170', '16', '4'],
 ['1', '56', '84', '362', '33', '82', '296', '40', '3'],
 ['10', '238', '149', '205', '96', '89', '223', '65', '5'],
 ['92', '142', '30', '237', '336', '140', '210', '50', '2']]

Note that map returns a map object in Python 3, so there you would need list(map(list, zip(*a)))

Using a list comprehension with zip(*...), this would work as is in both Python 2 and 3.

[list(x) for x in zip(*a)]

NumPy way:

>>> import numpy as np
>>> np.array(a).T.tolist()
[['AAA', 'BBB', 'CCC', 'DDD', 'EEE', 'FFF', 'GGG', 'HHH', 'III'],
 ['1', '262', '86', '48', '8', '39', '170', '16', '4'],
 ['1', '56', '84', '362', '33', '82', '296', '40', '3'],
 ['10', '238', '149', '205', '96', '89', '223', '65', '5'],
 ['92', '142', '30', '237', '336', '140', '210', '50', '2']]
like image 113
Ashwini Chaudhary Avatar answered Oct 13 '22 06:10

Ashwini Chaudhary


Through list comprehension:

[[x[i] for x in mylist] for i in range(len(mylist[0]))]
like image 2
sashkello Avatar answered Oct 13 '22 06:10

sashkello