[newbie] confusion concerning fetching an element in a 2d-array

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Mar 25 11:35:18 EDT 2014


On Tue, 25 Mar 2014 06:47:23 -0700, Jean Dubois wrote:

[...]
> Thanks for answering my question but unfortunately now I'm totally
> confused.
> Above I see parts from different programs which I can't assemble
> together to one working program (I really tried hard). Can I tell from
> your comment I shouldn't use numpy? 

No, you misunderstood me. I never suggested that you avoid numpy. If you 
read my code, I use numpy. That's the "import numpy as np", and then 
later I refer to np.

What I suggested is that you open up the Python interactive interpreter 
and use it for experimentation. Not that you avoid numpy! You will use 
numpy inside the interactive interpreter.

Do you know how to start the interactive interpreter? You seem to be 
using Linux, or maybe Mac. Open a console or xterm window, and type

python

then press Enter, and the interactive interpreter will start.


> I also don't see how to get the
> value an element specified by (row, column) from a numpy_array like
> "array_lines" in my original code

Once you build the array, you get the element the same way you tried (but 
failed) earlier:

print array_lines[1, 1]


will print the element at row 1, column 1. The problem you had before was 
that you had a one dimensional array, not a two dimensional one.


> All I need is a little python-example reading a file with e.g. three
> lines with three numbers per line and putting those numbers  as floats
> in a 3x3-numpy_array, then selecting an element from that numpy_array
> using it's row and column-number.

Yes, I'm sure you do. And you will learn much more by writing this code 
yourself.

You were very, very close with your earlier attempt. In English, you had:

* import the numpy module
* read the file into a list of text lines
* store the text lines in a numpy array
* try to print a single item from the array

but it failed because the list of lines was only one dimensional. I gave 
you some code that was very similar:

* import the numpy module
* fake a text file using a string
* split the string into a list of substrings
* convert each substring into a number (float)
* store the numbers in a numpy array
* change the size of the array to turn it from 1D to 2D
* print the array


Can you identify which part of code goes with each English description? 
That's your first job. Then identify the parts of code you want to take 
from my example and put it into your example.

Good luck, and have fun!



-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list