0

I need to loop through two matrixes, but I can't use Numpy, I'm asked not to use it.

altura_mar = [[1,5,7],
              [3,2,31]]
precipitacion_anual = [[10,5,70],
                       [5,7,8]]
for marIndex, anualIndex in zip(altura_mar, precipitacion_anual):
   #some code

so, my problem here is that zip works with just a list not a 2d list if I try to use it with a matrix it gives this error:"ValueError: too many values to unpack (expected 2)"

Now I'm thinking of two possible solutions:

  1. Make the multidimensional list into a single list like altura_mar = [1,5,7,3,2,31] but how could I do that?
  2. Work with the 2 matrixes as they are in a nested for loop (I don't know about this, but maybe you guys can help here).
Jeison AK
  • 23
  • 6

3 Answers3

0

Since it's a 2d list, you can apply the zip twice:

>>> for a,b in zip(altura_mar, precipitacion_anual):
...     for c,d in zip(a,b):
...             print(c,d)
...
1 10
5 5
7 70
3 5
2 7
31 8

This solution does not scale well when the nest depth is variable, though.

UziGoozie
  • 178
  • 1
  • 7
0

I think the most basic solution is best, just iterating over the indices rather than nested zip statements (see this post)

>>> for i in range(len(altura_mar)):
...     for j in range(len(altura_mar[i])):
...         print(altura_mar[i][j], precipitacion_anual[i][j])
... 
1 10
5 5
7 70
3 5
2 7
31 8
falafelocelot
  • 548
  • 3
  • 12
0

Assuming you want to pair 1 with 10 not [1,5,7] with [10, 5, 70] then in addition to the other perfectly fine answers, you could also use list comprehension generators like:

altura_mar = [[1,5,7], [3,2,31]]
altura_mar_flat = (cell for row in altura_mar for cell in row)

precipitacion_anual = [[10,5,70], [5,7,8]]
precipitacion_anual_flat = (cell for row in precipitacion_anual for cell in row)

for marIndex, anualIndex in zip(altura_mar_flat, precipitacion_anual_flat):
    print(marIndex, anualIndex)

This also gives you:

1 10
5 5
7 70
3 5
2 7
31 8
JonSG
  • 10,542
  • 2
  • 25
  • 36
  • 1
    That's beautiful code, I really like list comprehension :,) this sure is a good way to flatten a multidimensional list! – Jeison AK Jun 07 '21 at 15:32