Home python Entering a two-dimensional array with Python keyboard

Entering a two-dimensional array with Python keyboard

Author

Date

Category

I want to create a rectangular matrix, the numbers of which can be entered from the keyboard, but gives an error. Or how can I do this differently?

a = []
For i in Range (5):
  For j in Range (5):
    A [I, J] = INT (INPUT ())
    Print (A)

Answer 1

Your matrix is ​​essentially not one structure, but a list of nested lists.

That is, you can not immediately refer to the cell on a dual index A [I, J]

Instead, you must first contact one index (i) to access the nested list, and therefore inside it on the second index (j) access the specific cell.

That is, you need to write these two indexes not in some brackets, but in different after each other:

a [i] [j] = int (input ())

Well, the first line you need to change on

a = [[0 for n in range (5)] for nn in range (5)]

Otherwise, you have an empty source list, and you are trying to access non-existent elements, and it turns out an error.

PS: In the future, when you create a question, always give the full text of the error. Otherwise, it is sometimes very difficult to guess what the problem is.


Answer 2

a = []
For i in Range (5):
  a.append ([])
  For j in Range (5):
    A [i] + = [INT (INPUT ())]
    Print (A)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions