-1

What would be the best way to write input into a 2D array with an input of the full array like so:

f g p g s
k p o d z
k d c s t
v c r s m
a w c t e

I would be able to read it in easily if it was one value at a time, but the whole array as input all at once is confusing me. My first thought was to do something like

for i in range(amount_row):
        for j in range(amount_column):
            matrix[i][j] = input()

but that is not working because of the format of the input. I had the user input the dimensions of the matrix.

Simon
  • 1
  • 1
    How are you getting the input as a string? – Dani Mesejo Oct 12 '19 at 01:47
  • Possible duplicate of [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers) – wwii Oct 12 '19 at 01:48
  • What do you mean by "the format of the input"? For example, to get the array you showed, how many times should the user be asked to input, and what should each input look like? – Karl Knechtel Oct 12 '19 at 02:28

3 Answers3

0

You can try this:

matrix = [[]]

for i in range(amount_row):
    inp = input().split(' ')
    matrix.append([j for j in inp])

or:

matrix = [[j for j in input().split(' ')] for inp in range(amount_row)]
itskoi
  • 1
  • 1
0

As far I understand, you need the user to input the dimensions of the array and also you want to take all the numbers of the array at once and store it in the shape given by the user. You can do something like this using numpy:

import numpy as np

x,y=input("Enter dimensions (x,y)").split(",")
nums = input("Enter the list of numbers comma seperated").split(",")
nums = np.array(nums,dtype=int)
nums = np.reshape(nums,(int(x),int(y)))
print(nums)

The output is:

Enter dimensions (x,y)2,2
Enter the list of numbers comma seperated1,2,3,4
[[1 2]
 [3 4]]
Sree
  • 973
  • 2
  • 14
  • 32
-1
import numpy as np
two_d_array = []

print("Input the dimensions of the 2D array: ")
m = int(input())
n = int(input())

outer_list = []
inner_list = []

print("Enter the elements : ")

for i in range(m):
    inner_list = []
    for j in range(n):
        inner_list.append(int(input()))
    outer_list.append(inner_list)

print(outer_list)
matrix = np.array(outer_list)
print(matrix)

Hope the above code helps for you.

Stan11
  • 274
  • 3
  • 11