James Wright
James Wright

Reputation: 1423

Loop over list of lists and use ith iterator

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 ith 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

Answers (2)

Jean-François Fabre
Jean-François Fabre

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

Cory Kramer
Cory Kramer

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

Related Questions