简体   繁体   中英

How can a function handle a NumPy array input, which is not comma-separated?

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.

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

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 - 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM