I have an NumPy array with a shape of (2143, 3). I am trying to make a list consisting of a tuple containing 3 ints from the numpy array and 1 boolean.
This is the code I'm trying to modify:
Voxel = namedtuple('Voxel', 'x y z c')
#This is the tuple
voxels = [ Voxel( nz[0][i], nz[1][i], nz[2][i], True ) for i in range(nz[0].shape[0]) ]
#This is the list
For some reason I'm getting this error:
IndexError: tuple index out of range
Related
I work in the field of image processing, and I converted the image into a matrix. The values of this matrix are only two numbers: 0 and 255. I want to know where the value 0 is in which column and in which row it is repeated within this matrix. Please help
I wrote these
array = np.array(binary_img)
print("array",array)
for i in array:
a = np.where(i==0)
print(a)
continue
The == operator on an array returns a boolean array of True/False values for each element. The argwhere function returns the coordinates of the nonzero points in its parameter:
array = np.array(binary_img)
for pt in np.argwhere(array == 0):
print( pt )
def openMap(uArr, oArr, i):
y = int(input("Row Number"))
x = int(input("Column Number"))
uArr[y,x] = oArr[y,x]
printMap(uArr)
if oArr[y,x] == "X":
return 0
else:
return 1
uArr refers to the user array and oArr to the original array.
I get this error:
list indices must be integers or slices, not a tuple
Can someone help to debug this?
In a normal Python multidimensional list, you can't access elements as uArr[y, x]. Instead use uArr[y][x].
Perhaps you mean if oArr[y][x] == "X":? You cannot pass 2 numbers for indexing a list.
By passing [y,x] it means oArr[(y,x)] And list indexing needs an integer.
You should do:
if oArr[y][x] == "X":
The error-message indicates a common syntax error in Python.
Syntax-error when indexing
list indices must be integers or slices, not a tuple
It is caused by using the wrong syntax when indexing a list (or array). What your code used as index was x,y was interpreted as tuple like (x,y).
Correct would be either a single integer, like array[1] or array[x] or a slice like array[1:2] to get second to third element.
See explained in article TypeError: list indices must be integers or slices, not str.
The indexes in any multi-dimensional array or list must be added in separate brackets. So [x][y][z] indexes a single element in a cube or 3D-array, whereas your 2-dimensional array will just use something like [x][y].
Hot to fix
To fix it, simply replace all [y,x] by [y][x].
def openMap(uArr, oArr, i):
y = int(input("Row Number"))
x = int(input("Column Number")) # fixed a typo
uArr[y][x] = oArr[y][x]
printMap(uArr)
if oArr[y][x] == "X":
return 0
else:
return 1
Bonus-Tip: Validate user-input to avoid out-of-bounds errors
What happens if the user enters -1 or 999999999999? Does your array or list allow negative indices or have a size that large?
You should check before and ask for a correct input then.
last_row = len(oArr)-1 # last index because zero-based
y = last_row + 1 # initially out-of-bounds to enter the loop
while not 0 <= y <= last_row:
y = int(input("Row Number ({}..{}): ".format(0, last_row)))
last_col = len(oArr[0])-1 # suppose it's quadratic = all rows have same length
x = last_col + 1 # initially out-of-bounds to enter the loop
while not 0 <= x <= last_col:
x = int(input("Column Number ({}..{}):".format(0, last_col)))
Note: Technically a negative index like -1 will point to the last element, -2 to the element before last, and so on.
See also related questions:
Determine Whether Integer Is Between Two Other Integers?
How to index a list based on user input, and print the result
IndexError: list index out of range : when a element is poped out of array in python
Python - Input Validation
I have a 2D array "pop" in python. I want to multiply each element of column one with an integer. I used the following code
temp[i] = b*pop[i,0]+a*pop[i,1]
But it is returning error "list indices must be integers or slices, not tuple"
import random
from random import sample
rows=20
a,b = 0.5,1
pop=list(zip(sample(range(1, 100000), rows),sample(range(1, 100000), rows)))
profit = sample(range(1, 100000), rows)
#print(pop,profit)
mycombined=list(zip(pop,profit))
combined_array = np.asarray(mycombined)
print(combined_array)
m = len (combined_array)
it = 1500
#alpha = 0.01
J=0
for i in range(1,m,1):
bpop=combined_array[i][0][0]
apop=combined_array[i][0][1]
aprofit=combined_array[i][1]
temp=(bpop+apop-aprofit)**2
J=J+temp
Now you have a list of lists and can use list comprehensions to change the values
pop contains a two variable tuple
profit is a list of random numbers
the result is a list of lists or tuples
I want to compare all elements of a two-dimensional list
array with a float
x.
The result should be a list:
b = [[True, False,...],...].
I tried it like that:
import numpy as np
array = [[a1,a2,...], [a3,a4,...],...,]
x = 2.0
b = np.array([a >= x for a in array])`
"TypeError: '>=' not supported between instances of 'list' and 'float'"
When I use a one-dimensional list it works fine.
Thanks in advance!!
b = np.array([[a >= x for a in row] for row in array])
I'm trying to create a bidimensional array using list comprehension.
a = [[0 for y in range(1, 10)] for x in range(1, 10)]
This should create a 9x9 'matrix' whose first item is a[1][1], and last is a[9][9]
However this is not happening, and when I try to print the last element:
print(a[9][9])
I get an out of range error.
What am I doing wrong?
You do have a 9x9 matrix (or list of lists), but since indices are zero based, you can only index from 0 to 8 along both axes.
The start value 1 in the range function does not influence the start value of your indexing; it will always be zero.