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]
Mojtaba Kamyabi
3,6703 gold badges33 silver badges52 bronze badges
asked May 16, 2020 at 15:15
ademola adelakun
111 silver badge4 bronze badges
2 Answers 2
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
ademola adelakun
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
David
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]i = 0 and just after while (i == 2): are not compatible
answered May 16, 2020 at 15:22
Renaud
2,8172 gold badges12 silver badges25 bronze badges
Comments
lang-py
whileloop is a no-op since there is no way forito be 2. You might need to include more of your actual code.i != 2.