ademola adelakun
ademola adelakun

Reputation: 11

Array loop not returning expected output in Python

pressures = [[5,6,7],
             [8,9,10],
             [11,12,13],
             [14,15,16]]
i = 0
while (i == 2):
    for row in pressures[i:]:
        cycle[i] = row[i]
row[1]

Please any idea why the above code is returning just the last value of the array which is 15

I expect the output to be ;

[ 6,
  9,
 12,
 15]

Upvotes: 0

Views: 139

Answers (2)

David
David

Reputation: 444

If all you want is the middle column returned, then you can do that by iterating through the rows and taking the 1 element:

pressures = [[5,6,7],
             [8,9,10],
             [11,12,13],
             [14,15,16]]


middle_col = []
for row in pressures:
    middle_col.append(row[1])

Equivalently, you can do this in one line:

pressures = [[5,6,7],
             [8,9,10],
             [11,12,13],
             [14,15,16]]

middle_col = [row[1] for row in pressures]

The best way, though, is probably to use NumPy with array indexing:

import numpy as np

pressures = np.array([[5,6,7],
                      [8,9,10],
                      [11,12,13],
                      [14,15,16]])

middle_col = pressures[:, 1]

which will return a numpy array which looks like np.array([6,9,12,15]).

Upvotes: 3

Renaud
Renaud

Reputation: 2819

i = 0 and just after while (i == 2): are not compatible

Upvotes: 0

Related Questions