我如何在python中将4d数组转换为2d数组?

时间:2019-02-23 14:50:36

标签: python python-3.x

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)

程序输入为

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']]], [[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]]]

我怎么能变成这样的二维数组

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

1 个答案:

答案 0 :(得分:1)

尝试使用列表推导,并使用splitlines遍历行,然后拆分行,然后将值转换为整数:

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