So I have something like :
l1=[1,2,3]
l2=[4,5,6]
l3=[7,8,9]
Expected output is : ls=[[1,4,7],[2,5,8],[3,6,9]]
What it will be the most corect way to do that?
So I have something like :
l1=[1,2,3]
l2=[4,5,6]
l3=[7,8,9]
Expected output is : ls=[[1,4,7],[2,5,8],[3,6,9]]
What it will be the most corect way to do that?
Use zip
and then list comprehension to turn the tuple
s into list
s
[list(x) for x in zip(l1, l2, l3)]
Result:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
>>> l1=[1,2,3]
>>> l2=[4,5,6]
>>> l3=[7,8,9]
>>> zip(l1, l2, l3)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
The built-in function zip will help you with what you want.
zip
the three lists:
>>> l1 = [1,2,3]
>>> l2 = [4,5,6]
>>> l3 = [7,8,9]
>>> zip(l1,l2,l3)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Use a list comprehension to cast the tuples into lists to have a list of lists:
>>> [list(i) for i in zip(l1,l2,l3)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]