31

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', ...],
...
...]
sashkello
  • 17,306
  • 24
  • 81
  • 109
Robert
  • 651
  • 1
  • 6
  • 18
  • In case you list of lists is not square, you can find a solution here: http://stackoverflow.com/a/38815389/2521204 – 1man Aug 07 '16 at 15:08
  • 1
    Does this answer your question? [Transpose list of lists](https://stackoverflow.com/questions/6473679/transpose-list-of-lists) – mkrieger1 Apr 15 '22 at 16:13

4 Answers4

59

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']]
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
3

Through list comprehension:

[[x[i] for x in mylist] for i in range(len(mylist[0]))]
sashkello
  • 17,306
  • 24
  • 81
  • 109
1

You can also use

a= np.array(a).transpose().tolist()
0

You could also do:

row1 = [1,2,3]
row2 = [4,5,6]
row3 = [7,8,9]

matrix = [row1, row2, row3]
trmatrix = [[row[0] for row in matrix],[row[1] for row in matrix],  [row[2] for row in matrix]]
evertjanh
  • 51
  • 1
  • 4