3

Using Python I want to convert:

outputlist = []

list = [[1,2,3],[a,b,c],[p,q,r]]
outputlist =[[1,a,p],[2,b,q],[3,c,r]]

How do I do this?

outputlist.append([li [0] for li in list ])

it yields

[1,a,p]

not the other items. I need it for all of the items.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135

3 Answers3

6

You want to use zip:

Code:

lst = [[1,2,3],['a','b','c'],['p','q','r']]

print(zip(*lst))

Results:

[(1, 'a', 'p'), (2, 'b', 'q'), (3, 'c', 'r')]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
1

You can try with numpy:

>>> import numpy as np
>>> l = [ [1,2,3],['a','b','c'],['p','q','r']]
>>> np.array(l).T.tolist()
[['1', 'a', 'p'], ['2', 'b', 'q'], ['3', 'c', 'r']]
shizhz
  • 11,715
  • 3
  • 39
  • 49
0
list = [[1,2,3],[a,b,c],[p,q,r]]
outputlist = zip(*list)

zip() returns the elements as tuples, covert them to lists if that's exactly what you require.

Gautham Kumaran
  • 421
  • 5
  • 15