I’m new here and i have such problem:
I need to print even columns of matrix. When i tried to do this i’ve got such error:
print(array[:, 1::2])
TypeError: list indices must be integers or slices, not tuple
Here is what i tried to solve this problem:
import numpy as np
import random
arr = []
rows = int(input('\nInput the number of rows: '))
cols = int(input('Input the number of cols: '))
def AutoFill(rand_arr, rows, cols):
for k in range(rows):
arr = []
for v in range(cols):
a = random.randint(-20, 20)
arr.append(a)
rand_arr.append(arr)
rand_arr = np.array([])
return rand_arr
def PrintArr(array):
print('Your matrix: ')
print(np.matrix(array))
def EvenCols(array):
print(array[:, 1::2])
AutoFill(arr, rows, cols)
PrintArr(arr)
EvenCols(arr)
>Solution :
arr is a vanilla Python list, not a numpy array. You can’t use tuple indexing on vanilla Python lists.
There are two ways to fix this:
- You should transform
arrto a numpy array before you pass it intoEvenCols(), like so:
EvenCols(np.array(arr))
You can then remove the last two lines of the AutoFill function, since this method modifies the list in-place.
- Methods that have side effects can make it harder for others to understand your code. While for this short example it may be fine, a better approach would be to create a new list, in the function, return it, and assign the function’s return value to
arr, like so:
def AutoFill(rows, cols):
rand_arr = []
for k in range(rows):
arr = []
for v in range(cols):
a = random.randint(-20, 20)
arr.append(a)
rand_arr.append(np.array(arr))
return np.array(rand_arr)
Then, the last three lines would look like:
arr = AutoFill(rows, cols)
PrintArr(arr)
EvenCols(np.array(arr))
Additionally, in this approach, the initial assignment to arr at the top of your code snippet can be removed.