0

I want to change only the place in the list called numbers.

So if is numbers=[4,8,11], I want to change 4>>field[0,5]=1,8>>field[0,9]=1,11>>field[1,0]=1

Number in list numbers are 0 to 100. I run this,but it's says 'TypeError: 'function' object does not support item assignment'

How can I solve this? And is there better way to check each number and set 1 at 2D array?

Here is my code

import numpy as np

field = np.zeros((10,10),dtype=int)

def change_numbers(numbers):
    for i in numbers:
        if 1 <= i <= 10:
            i -= 1
            p1_field[0,i] = 1
        elif 11 <= i <= 20:
            i -= 1
            p1_field[1,i] = 1
        elif 21 <= i <= 30:
            i -= 1
            p1_field[2,i] = 1
        elif 31 <= i <= 40:
            i -= 1
            p1_field[3,i] = 1
        elif 41 <= i <= 50:
            i -= 1
            p1_field[4,i] = 1
        elif 51 <= i <= 60:
            i -= 1
            p1_field[5,i] = 1
        elif 61 <= i <= 70:
            i -= 1
            p1_field[6,i] = 1
        elif 71 <= i <= 80:
            i -= 1
            p1_field[7,i] = 1
        elif 81 <= i <= 90:
            i -= 1
            p1_field[8,i] = 1
        elif 91 <= i <= 100:
            i -= 1
            p1_field[9,i] = 1
    print(field)
2
  • What is p1_field? Commented Jun 22, 2020 at 4:59
  • Sorry. It's my mistake. field == p1_field Commented Jun 22, 2020 at 5:08

1 Answer 1

1
  1. To define a function to change the elements of an array, it's better to put the array as an input of the function. This may explain the error message you encountered.
  2. There is a better way to do the job you desired.

Here's the code:

def change_numbers(array, numbers):
    for i in numbers:
        array[(i - 1)//10, i-1] = 1

The last line basically does the whole long 'if' clauses. (i - )//10 returns 0, 1, 2, ... for the conditions in your code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.