I wrote a function to modify a 2D NumPy array:
def fun(state,r,c):
state = np.array(state)
state[r][c] = 0
return state
To test it, I used this format:
state = np.array([[1, 1, 1, 0, 1, 1, 1, 0, 1],[0, 1, 1, 1, 1, 1, 1, 0, 1]])
However this function should also handle input, where the array is not comma separated:
state=
[[1 1 1 1 1]
[1 0 0 0 1]
[0 0 0 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]
How can this function handle the NumPy array input, which is not comma-separated? Whatever I tried so far to fix it, a SyntaxError was raised.
Thank you very much for your help.
CodePudding user response:
Be careful to distinguish things like list
, array
and strings - their displays.
Here's your syntax error:
In [412]: state=
...: [[1 1 1 1 1]
...: [1 0 0 0 1]
...: [0 0 0 1 1]
...: [1 1 1 1 1]
...: [1 1 1 1 1]]
File "<ipython-input-412-1d0565808329>", line 1
state=
^
SyntaxError: invalid syntax
That is not valid python. But it does look like the print display of an array, a string.
You can make a multiline string:
In [413]: state="""
...: [[1 1 1 1 1]
...: [1 0 0 0 1]
...: [0 0 0 1 1]
...: [1 1 1 1 1]
...: [1 1 1 1 1]]"""
In [414]: state
Out[414]: '\n[[1 1 1 1 1]\n [1 0 0 0 1]\n [0 0 0 1 1]\n [1 1 1 1 1]\n [1 1 1 1 1]]'
In [415]: type(state)
Out[415]: str
Your first case starts with a list:
In [417]: state = [[1, 1, 1, 0, 1, 1, 1, 0, 1],[0, 1, 1, 1, 1, 1, 1, 0, 1]]
In [418]: state
Out[418]: [[1, 1, 1, 0, 1, 1, 1, 0, 1], [0, 1, 1, 1, 1, 1, 1, 0, 1]]
In [419]: type(state)
Out[419]: list
an array made from the list:
In [420]: arr = np.array(state)
In [421]: arr
Out[421]:
array([[1, 1, 1, 0, 1, 1, 1, 0, 1],
[0, 1, 1, 1, 1, 1, 1, 0, 1]])
The print display of the array:
In [422]: print(arr)
[[1 1 1 0 1 1 1 0 1]
[0 1 1 1 1 1 1 0 1]]
That print display is not intended for parsing, recreating an array. While it's not impossible, I think a beginner should not go there. There are more important things to learn.