Reputation: 1423
So I have the following list of lists:
test = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
I would like to loop over the i
th element in the inner lists. I can do this by using zip
:
for x, y, z in zip(test[0], test[1], test[2]):
print(x, y, z)
Which returns:
1 4 7
2 5 8
3 6 9
Is there a cleaner, more Pythonic way to do this? Something like zip(test, axis=0)
?
Upvotes: 1
Views: 2020
Reputation: 140186
You can use unpacking to pass the sublists of your input to zip
as variable arguments:
for xyz in zip(*test):
print(*xyz)
(and you can do the same for the x,y,z coords to pass params to print
)
Upvotes: 5
Reputation: 117886
If you use numpy.array
you can simply use the transpose
of the array and iterate over the rows
>>> import numpy as np
>>> test = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> t = np.array(test)
>>> t
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Then to iterate
for row in t.T:
print(row)
[1 4 7]
[2 5 8]
[3 6 9]
Depending what you intend to do, numpy
will likely be more efficient than list comprehensions in general
Upvotes: 0