Python Checking the Value of an Element in an Array
Question:
In my program, I generate two lists each with 10 integers: one through user input, and one through random selection. Then, using numpy
, I convert one of the lists into a 2×5 array, and the other into a 5×2 array and take the outer product to arrive at a 5×5 array like this:
[[ 1 1 1 1 1]
[ 1 1 1 1 1]
[ 1 1 0 1 1]
[ 1 1 1 1 1]
[ 1 1 1 1 1]]
I want to ask the user some questions about the array, for example, “What is the value in the center of the resulting array?” (which would be 0 in this case).
How can I have Python check the value of the integer at the center of the array?
Answers:
If your array is arr
, arr[2,2]
will return the 3rd value down and 3rd value across (because indexing starts with 0). See the documentation.
If your array is a square array with odd dimensions you can do
x.ravel()[x.size/2]
Given the you are asking for the center, i am assuming that your array is going to have odd dimensions. if that is the case you could use the following:
print arr[len(arr)/2][len(arr[1])/2]
this divides the number of rows and columbs by 2 which will give you the middle index.
In my program, I generate two lists each with 10 integers: one through user input, and one through random selection. Then, using numpy
, I convert one of the lists into a 2×5 array, and the other into a 5×2 array and take the outer product to arrive at a 5×5 array like this:
[[ 1 1 1 1 1]
[ 1 1 1 1 1]
[ 1 1 0 1 1]
[ 1 1 1 1 1]
[ 1 1 1 1 1]]
I want to ask the user some questions about the array, for example, “What is the value in the center of the resulting array?” (which would be 0 in this case).
How can I have Python check the value of the integer at the center of the array?
If your array is arr
, arr[2,2]
will return the 3rd value down and 3rd value across (because indexing starts with 0). See the documentation.
If your array is a square array with odd dimensions you can do
x.ravel()[x.size/2]
Given the you are asking for the center, i am assuming that your array is going to have odd dimensions. if that is the case you could use the following:
print arr[len(arr)/2][len(arr[1])/2]
this divides the number of rows and columbs by 2 which will give you the middle index.