cem h
cem h

Reputation: 21

How I can turn into 4d array to 2d array in Python?

row=int(input("Number of rows for two dimensional list please:")) 
print("Enter",row,"rows as a list of int please:")

numbers = []
for i in range(row):
    numbers.append(input().split())
array=[0]*row
for i in range(row):
    array[i]=[numbers]



print(array)

The program inputs are

1 2 3
4 5 6
7 8 9

This program output:

[[[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]], [[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]], [[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]]]

How can I turn into this 2 dimensional array like this

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Upvotes: 0

Views: 155

Answers (1)

U13-Forward
U13-Forward

Reputation: 71560

Try using a list comprehension, and iterate trough the lines, using splitlines, then split the lines, then convert the values to an integer:

row=input("Number of rows for two dimensional list please:")
print([list(map(int,i.split())) for i in row.splitlines()])

Upvotes: 1

Related Questions