0
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]
4
  • 3
    This code doesn't return anything, and the while loop is a no-op since there is no way for i to be 2. You might need to include more of your actual code. Commented May 16, 2020 at 15:20
  • 2
    Please recheck/reformat your code. It does not return anything because the while loop never runs, since i != 2. Commented May 16, 2020 at 15:20
  • When reformatting your code as recommended above, please also make sure the indentation level is correct for each line Commented May 16, 2020 at 15:21
  • You probably want an if statement inside another for loop instead of the while loop. Commented May 16, 2020 at 15:22

2 Answers 2

3

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]).

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you this solves my problem. But what if I need to loop through I.e to return any column I specify not just one at a time. That will be very helpful. Thanks
you just loop through the indices of the columns. instead of row[1], it would be row[i] where i is your iteration variable. Likewise for pressures[:,i]
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.