Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge lists inside the list in python [duplicate]

Tags:

python

list

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.

like image 489
Manikandan Duraisamy Avatar asked Sep 03 '26 23:09

Manikandan Duraisamy


2 Answers

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')]
like image 153
Stephen Rauch Avatar answered Sep 06 '26 13:09

Stephen Rauch


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']]
like image 23
shizhz Avatar answered Sep 06 '26 11:09

shizhz



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!