4.11. Array Iteration

4.11.1. 1-dimensional Array

import numpy as np


a = np.array([1, 2, 3])

for obj in a:
    print(obj)

# 1
# 2
# 3

4.11.2. 2-dimensional Array

import numpy as np


a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

for obj in a:
    print(obj)

# [1 2 3]
# [4 5 6]
# [7 8 9]
import numpy as np


a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

for row in a:
    for obj in row:
        print(obj)

# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9

4.11.3. Flat

4.11.3.1. Flatten

import numpy as np


a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

for obj in a.flatten():
    print(obj)

# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9

4.11.3.2. Ravel

import numpy as np


a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

for obj in a.ravel():
    print(obj)

# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9

4.11.4. Enumerate

a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])

for i, obj in enumerate(a):
    print(i, obj)

# 0 [1 2 3]
# 1 [4 5 6]
# 2 [7 8 9]

4.11.5. Assignments

4.11.5.1. Iteration

English
  1. Use data from "Input" section (see below)

  2. Given a: ndarray (see below)

  3. Use for to iterate over a

  4. Print even numbers

Polish
  1. Użyj danych z sekcji "Input" (patrz poniżej)

  2. Dany a: ndarray (patrz sekcja input)

  3. Używając for iteruj po DATA

  4. Wypisz liczby parzyste

Input
DATA = np.array([[1, 2, 3],
                  [4, 5, 6],
                  [7, 8, 9]])
The whys and wherefores
  • Iterating 2-dimensional ndarray

Hint
  • number % 2 == 0